为什么DataBinding不起作用?

时间:2010-07-04 17:08:39

标签: c# wpf data-binding

为什么DataBinding不起作用?

<TextBox Text="{Binding Path=local:MainWindow.SearchPlayer,
    Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"  />

这是我的班级:

  public partial class MainWindow : Window
    {
        private Store store = new Store();
        private string _searchPlayer;
        public string SearchPlayer
        {
            get
            {
                return _searchPlayer;
            }
            set
            {
                _searchPlayer = value;
                if(_searchPlayer!="")
                {
                    ACT.DataContext = store.SearchedPlayers
                      .Where(x => x.StartsWith(_searchPlayer)).ToList();
                }
                else
                {
                    ACT.DataContext = store.Last10SearchedPlayers;
                }
            }
        }

        public MainWindow()
        {...............}

我在SearchPlayer setter上设置了断点,但它从未起作用。

2 个答案:

答案 0 :(得分:3)

<TextBox Text="{Binding Path=SearchPlayer,
                        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}
                        Mode=TwoWay,
                        UpdateSourceTrigger=PropertyChanged}"  />

答案 1 :(得分:2)

我认为Binding Path=local:MainWindow.SearchPlayer不会起作用,因为MainWindow是一个类,而不是一个实例。如果SearchPlayer是静态的,它可能会起作用,但我不认为你想要那样。

只需使用Binding Path=SearchPlayer并确保正确设置DataContext。在MainWindow的构造函数中:this.DataContext=this;(根据文本框的位置而有所不同)。

请注意,MainWindow应该实现INotifyProperty接口,而SearchPlayer的Setter应该调用OnPropertyChanged。

相关问题