簡體   English   中英

WPF CheckBox雙向綁定不起作用

[英]WPF CheckBox TwoWay Binding not working

我有

 <DataGridCheckBoxColumn 
     Binding="{Binding Path=Foo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
 />

 public bool Foo{ get; set; }

檢查/取消檢查設置Foo ,但在代碼中設置Foo不會更改復選框狀態。 任何建議?

當您在DataContext設置 Foo 時,您需要引發PropertyChanged事件。 通常,它看起來像:

public class ViewModel : INotifyPropertyChanged
{
    private bool _foo;

    public bool Foo
    {
        get { return _foo; }
        set
        {
            _foo = value;
            OnPropertyChanged("Foo");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

如果您調用Foo = someNewvalue ,將引發PropertyChanged事件並且您的 UI 應該更新

我花了幾個小時尋找這個問題的完整答案。 我猜有些人認為搜索這個問題的其他人知道基本知識 - 有時我們不知道。 關於設置表單數據上下文的一個非常重要的部分通常會丟失:

    public YourFormConstructor()
    {
        InitializeComponent();
        DataContext = this;                 // <-- critical!!
    }

我的復選框控件是在 xaml 文件中設置的,如下所示:

<CheckBox x:Name="chkSelectAll" IsChecked="{Binding chkSelectAllProp, Mode=TwoWay}" HorizontalAlignment="Left"/>

“Path=”和“UpdateSourceTrigger=...”部分似乎是可選的,所以我將它們排除在外。

我在 ListView 標題列中使用此復選框。 當有人選中或取消選中復選框時,我希望 ListView 中的所有項目也被選中或取消選中(選擇/取消選擇所有功能)。 我在示例中留下了該代碼(作為“可選邏輯”),但您的復選框值邏輯(如果有)將替換它。

The ListView contents are set by browsing for a file, and when a new file is selected, code sets the ListView ItemsSource and the CheckBox is checked (selecting all the new ListView items), which is why this two-way operation is required. 此示例中不存在該部分代碼。

xaml.cs 文件中用於處理 CheckBox 的代碼如下所示:

    // backing value
    private bool chkSelectAllVal;

    // property interchange
    public bool chkSelectAllProp
    {
        get { return chkSelectAllVal; }
        set
        {
            // if not changed, return
            if (value == chkSelectAllVal)
            {
                return;
            }
            // optional logic
            if (value)
            {
                listViewLocations.SelectAll();
            }
            else
            {
                listViewLocations.UnselectAll();
            }
            // end optional logic
            // set backing value
            chkSelectAllVal = value;
            // notify control of change
            OnPropertyChanged("chkSelectAllProp");
        }
    }

    // object to handle raising event
    public event PropertyChangedEventHandler PropertyChanged;

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM