programing

WPF 체크박스바인딩

fastcode 2023. 4. 15. 09:31
반응형

WPF 체크박스바인딩

체크박스의 클릭 이벤트를 사용하여 체크박스의 체크상태를 변수에 저장하는 것은 간단한 일이지만, 데이터 바인딩을 통해 어떻게 해야 합니까?제가 찾은 모든 예제는 UI가 일부 데이터 소스에서 업데이트되었거나 한 컨트롤이 다른 컨트롤로 바인딩되어 있습니다. 이 체크박스를 클릭하면 멤버 변수를 업데이트하고 싶습니다.

TIA는 어떤 조언이라도...

바인딩을 양방향으로 해야 합니다.

<checkbox IsChecked="{Binding Path=MyProperty, Mode=TwoWay}"/>

여기에는 종속성 속성이 필요합니다.

public BindingList<User> Users
{
    get { return (BindingList<User>)GetValue(UsersProperty); }
    set { SetValue(UsersProperty, value); }
}

public static readonly DependencyProperty UsersProperty =
    DependencyProperty.Register("Users", typeof(BindingList<User>), 
      typeof(OptionsDialog));

이 작업이 완료되면 다음 종속 속성에 확인란을 바인딩합니다.

<CheckBox x:Name="myCheckBox"
          IsChecked="{Binding ElementName=window1, Path=CheckBoxIsChecked}" />

이를 수행하려면 열기 태그에 Window 또는 UserControl 이름을 지정하고 ElementName 파라미터에서 이 이름을 사용해야 합니다.

이 코드를 사용하면 코드 측의 속성을 변경할 때마다 텍스트 상자를 변경할 수 있습니다.또한 텍스트 상자를 선택하거나 선택 취소할 때마다 종속성 속성도 변경됩니다.

편집:

종속성 속성을 만드는 쉬운 방법은 스니펫 propdp를 입력하는 것입니다. 그러면 종속성 속성에 대한 일반 코드가 제공됩니다.

모든 코드:

XAML:

<Window x:Class="StackOverflowTests.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" x:Name="window1" Height="300" Width="300">
    <Grid>
        <StackPanel Orientation="Vertical">
            <CheckBox Margin="10"
                      x:Name="myCheckBox"
                      IsChecked="{Binding ElementName=window1, Path=IsCheckBoxChecked}">
                Bound CheckBox
            </CheckBox>
            <Label Content="{Binding ElementName=window1, Path=IsCheckBoxChecked}"
                   ContentStringFormat="Is checkbox checked? {0}" />
        </StackPanel>
    </Grid>
</Window>

C#:

using System.Windows;

namespace StackOverflowTests
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public bool IsCheckBoxChecked
        {
           get { return (bool)GetValue(IsCheckBoxCheckedProperty); }
           set { SetValue(IsCheckBoxCheckedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for 
         //IsCheckBoxChecked.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsCheckBoxCheckedProperty =
            DependencyProperty.Register("IsCheckBoxChecked", typeof(bool), 
            typeof(Window1), new UIPropertyMetadata(false));

        public Window1()
        {             
            InitializeComponent();
        }
    }
}

뒤에 있는 유일한 코드는 종속성 속성입니다.라벨과 체크박스가 모두 여기에 바인딩되어 있습니다.체크박스가 변경되면 라벨도 변경됩니다.

안녕하세요, 저는 처음 글을 올렸기 때문에 조금만 기다려 주세요.제 답변은 심플한 속성을 만드는 것이었습니다.

public bool Checked { get; set; }

그런 다음 확인란(cb1)의 데이터 컨텍스트를 설정합니다.

cb1.DataContext = this;

그런 다음 IsChecked proerty를 xaml로 바인드합니다.

IsChecked="{Binding Checked}"

코드는 다음과 같습니다.

XAML

<CheckBox x:Name="cb1"
          HorizontalAlignment="Left"
          Margin="439,81,0,0"
          VerticalAlignment="Top"
          Height="35" Width="96"
          IsChecked="{Binding Checked}"/>

코드 배후에 있다

public partial class MainWindow : Window
{
    public bool Checked { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        cb1.DataContext = this;
    }

    private void myyButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(Checked.ToString());
    }
}

그것보다 쉬울 거야사용방법:

<Checkbox IsChecked="{Binding Path=myVar, UpdateSourceTrigger=PropertyChanged}" />

데이터 클래스에 "MyProperty" 속성이 있는 경우 IsChecked를 다음과 같이 바인딩합니다.(컨버터는 옵션이지만 경우에 따라서는 필요)

<Window.Resources>
<local:MyBoolConverter x:Key="MyBoolConverterKey"/>
</Window.Resources>
<checkbox IsChecked="{Binding Path=MyProperty, Converter={StaticResource MyBoolConverterKey}}"/>

이것은 나에게 유효합니다(필수 코드만 포함되어 있습니다.필요에 따라 더 기입해 주세요).

XAML에서는 사용자 제어가 정의됩니다.

<UserControl x:Class="Mockup.TestTab" ......>
    <!-- a checkbox somewhere within the control -->
    <!-- IsChecked is bound to Property C1 of the DataContext -->
    <CheckBox Content="CheckBox 1" IsChecked="{Binding C1, Mode=TwoWay}" />
</UserControl>

UserControl의 코드 배후에 있습니다.

public partial class TestTab : UserControl
{
    public TestTab()
    {
        InitializeComponent();  // the standard bit

    // then we set the DataContex of TestTab Control to a MyViewModel object
    // this MyViewModel object becomes the DataContext for all controls
         // within TestTab ... including our CheckBox
         DataContext = new MyViewModel(....);
    }

}

솔루션 클래스의 MyViewModel이 정의되어 있다.

public class MyViewModel : INotifyPropertyChanged 
{
    public event PropertyChangedEventHandler PropertyChanged;
    private bool m_c1 = true;

    public bool C1 {
        get { return m_c1; }
        set {
            if (m_c1 != value) {
                m_c1 = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("C1"));
            }
        }
    }
}

백엔드 및 ViewModel 코드 없음:

다른 컨트롤의 가시성을 제어하기 위해 이 확인란을 만들었습니다.

<CheckBox x:Name="rulerCheckbox" Content="Is Ruler Visible" IsChecked="True"/>

그리고 다른 컨트롤에서는 그런 바인딩을 추가했습니다.

Visibility="{Binding IsChecked, ElementName=rulerCheckbox, Mode=TwoWay, Converter={StaticResource BoolVisConverter}}">

언급URL : https://stackoverflow.com/questions/870163/wpf-checkbox-binding

반응형