[英]WPF ToggleButton Binding Not Working
我有兩個ToggleButtons; 我試圖通過將它們綁定到布爾值來使它們像一對單選按鈕一樣工作,但是它不起作用。 這是我到目前為止的內容:
<ToggleButton Name="YesButton" Margin="5,0" Width="100" IsChecked="{Binding YesBool, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">Yes!</ToggleButton>
<ToggleButton Name="NoButton" Margin="5,0" Width="100" IsChecked="{Binding NoBool, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">No!</ToggleButton>
和
public partial class MainWindow : Window
{
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
}
public class Thingy : INotifyPropertyChanged
{
private bool _yesno;
public bool YesBool
{
get { return _yesno; }
set { _yesno = value; NotifyPropertyChanged("YesBool"); }
}
public bool NoBool
{
get { return !_yesno; }
set { _yesno = !value; NotifyPropertyChanged("NoBool"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
據我所知,遇到此問題的其他所有人都拼寫錯誤或未使用NotifyPropertyChanged,但是(據我所知)我正在做這兩種事情。 我究竟做錯了什么?
將您的xaml中的DataContext設置為Thingy類,而不是“ this”窗口。
您的問題是未指定布爾值是必需的還是僅用於幫助您獲得所需的行為。
因此,如果您不需要它們,也可以使用某個功能,取消選中另一個按鈕。 這也可以用於2個以上的ToggleButton。
如果可以確定除ToggleButtons之外沒有其他同類,那么也可以不進行類型檢查就進行foreach循環。
public void ToggleButtonChecked(object sender, RoutedEventArgs e)
{
ToggleButton btn = sender as ToggleButton;
if (btn == null)
return;
Panel container = btn.Parent as Panel;
if (container == null)
return;
for (int i = 0; i<container.Children.Count; i++)
{
if (container.Children[i].GetType() == typeof(ToggleButton))
{
ToggleButton item = (ToggleButton)container.Children[i];
if (item != btn && item.IsChecked == true)
item.IsChecked = false;
}
}
}
XAML
<ToggleButton x:Name="tb1" Checked="ToggleButtonChecked"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.