为什么wpf复选框绑定无法正常工作?

时间:2011-12-05 09:42:20

标签: c# wpf binding

关于复选框绑定问题的几个答案,例如this one表明

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

应该有效。我在以下代码中遗漏了什么,哪些不起作用?

<Window x:Class="TestBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <CheckBox Name="checkBox1" IsChecked="{Binding Path=MyProperty, Mode=TwoWay}">CheckBox</CheckBox>
    </Grid>
</Window>

namespace TestBinding
{
    public partial class Window1 : Window
    {
        bool property = true;

        public Window1()
        {
            InitializeComponent();
        }

        public bool MyProperty
        {
            get
            {
                return property;
            }
            set
            {
                property = value;
            }
        }
    }
}

更新

3个好的答案,非常感谢,我想接受所有这些,但已经接受了第一个提到DataContext,这是影响我最感兴趣的绑定方向的部分.TwoWay模式已经证明是一只红鲱鱼。 感谢MVVM建议,我正在使用它,但希望这段代码尽可能简单

3 个答案:

答案 0 :(得分:3)

您需要将DataContext设置为包含xaml绑定的属性的Object。在您的情况下,只需将Datacontext = this;放入c'tor。以及从每个绑定属性实现INotifyPropertyChanged接口和RaisePropertyChange。

正如其他人已经说过的,最好使用MVVM模式,在其中将属性存储在单独的类中而不是后面的UI代码中。

答案 1 :(得分:2)

您应该实现INotifyPropertyChanged并将DataContext绑定到此,然后它应该可以工作。

您可以在此处找到msdn链接:http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

但是你应该看看模式MVVM来处理你的wpf / silverlight窗口。它会让您的生活更轻松:http://en.wikipedia.org/wiki/Model_View_ViewModel

答案 2 :(得分:2)

实现INotifyPropertyChanged,并将DataContext设置为“this”:

namespace TestBinding
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged(String _Prop)
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(_Prop));
            }
        }
        #endregion

        bool property = true;

        public Window1()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        public bool MyProperty
        {
            get
            {
                return property;
            }
            set
            {
                property = value;
                RaisePropertyChanged("MyProperty");
            }
        }
    }
}
相关问题