【发布时间】:2012-01-30 14:54:44
【问题描述】:
我试图将 2 个不同的 WPF 控件绑定到 ViewModel 中的同一属性,即 CheckBox.IsChecked 和 Expander.IsExpanded。我想要实现的行为是让 CheckBox 影响 ViewModel(因此也影响 Expander),但不是其他方式绑定。 比如:
Checkbox Checked -> ViewModel property set to frue -> Expander.Expand
Checkbox Unchecked -> ViewModel property set to false -> Expander.Collapse
Expander Expanded -> Nothing else affected
Expander Collapsed -> Nothing else affected
这是 XAML:
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Expander IsExpanded="{Binding IsChecked, Mode=OneWay}">
<Expander.Header>
<CheckBox IsChecked="{Binding IsChecked}" Content="Is Checked"/>
</Expander.Header>
<TextBlock Text="Expanded!"/>
</Expander>
</Window>
和代码:
using System.ComponentModel;
using System.Windows;
namespace WpfApplication9
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public class ViewModel: INotifyPropertyChanged
{
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
NotifyPropertyChange("IsChecked");
}
}
protected void NotifyPropertyChange(string PropertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
}
现在我的问题是,当我单击 Expander 展开/折叠它时,Binding 似乎停止工作。谁能向我解释为什么会发生这种情况以及我该如何实现?提前致谢!
【问题讨论】: