[英]ToggleButton IsChecked Not Adhering to Bound Property
所以我有一個切換按鈕,如下所示:
<ToggleButton
IsChecked="{Binding IsButtonChecked, Mode=OneWay}"
Command="{Binding DoNothing}"
CommandParameter="{Binding ServerViewModel}"
Content="Click Me!"></ToggleButton>
IsButtonChecked 的初始值 = false
當我單擊切換按鈕時, ICommand 正確觸發(綁定到RelayCommand )並且此命令為 CanExecute 返回 false。 WPF ToggleButton 的 state 現在是 Checked=true,但是支持的 model 仍然是IsButtonChecked = false 。 為什么 UI 更新為選中的 state,即使綁定的屬性沒有?
我能夠阻止 UI 更新的唯一方法是創建一個反向屬性IsButtonNotChecked 。 然后,我將該屬性綁定到 XAML 中的IsEnabled 。如果當前啟用了 state,這將防止發生按鈕點擊。
您已將綁定模式設置為OneWay
,將其設置為TwoWay
。
<ToggleButton Command="{Binding DoNothing}"
CommandParameter="{Binding ServerViewModel}"
Content="Click Me!"
IsChecked="{Binding IsButtonChecked,
Mode=TwoWay}" />
對於它的價值,這就是我所做的。。它看起來確實很笨拙。
我將綁定模式設置為TwoWay。 看起來OneWay綁定不尊重IsChecked屬性。
<ToggleButton
IsChecked="{Binding IsButtonChecked, Mode=TwoWay}"
Command="{Binding DoNothing}"
CommandParameter="{Binding ServerViewModel}"
Content="Click Me!"></ToggleButton>
其次,我沒有選擇IsButtonChecked的mutator屬性。
public bool IsButtonChecked
{
get
{
return _isButtonChecked;
}
set
{
// Prevents the IsButtonCheckedfrom incorrectly being set to a
// enabled state, yet the model is false
// IsButtonCheckeddoesn't seem to respect OneWay binding.
}
}
然后,在后面的代碼中,我更新_isButtonChecked屬性並調用INotifyPropertyChanged事件。
internal void ShouldBeChecked(bool isChecked)
{
_isButtonChecked = isChecked;
OnPropertyChanged("IsButtonChecked");
}
雖然真的很笨拙。ToggleButton不尊重綁定屬性,這很奇怪。
正如我在此處的回答中所解釋的,只需將IsButtonChecked
屬性的PropertyChanged
事件作為DoNothing
命令中的第一個操作。 使用這種方法不需要扭曲綁定屬性。
如果需要,請查看參考答案以獲取更多詳細信息。 為了完整性而添加了這個答案,以引導人們找到這個問題,找到一個可能不那么笨拙的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.