Wpf TextBox数据绑定更新

时间:2013-02-25 12:13:18

标签: c# wpf data-binding

我有一个TextBox,它绑定到一个字符串属性:

文本框:

<TextBox x:Name="SearchBox"
     Text="{Binding SearchText, Source={StaticResource SearchEngine}, Mode=TwoWay}"
</TextBox>

和绑定到的类:

public class SearchEngine : ViewModelBase 
{
    private string _searchText = string.Empty;

    public SearchEngine() {
        Console.Out.WriteLine("this = {0}", this);
        SearchText = "Search";
    }

    public string SearchText 
    {
        get { return _searchText; }
        set 
        {
            if (_searchText != value) 
            {
                _searchText = value;
                Console.Out.WriteLine("AAAAAAAAAAAA: " + value);
                NotifyPropertyChanged();
            }
        }
    }
}

问题是当我输入TextBox时,SearchText没有更新。

2 个答案:

答案 0 :(得分:0)

执行以下操作:

<TextBox x:Name="SearchBox" Text="{Binding SearchText, Mode=TwoWay}" />

并在您的代码隐藏中将DataContext属性分配给您的实例,即

SearchEngine searchEngine = new SearchEngine();
SearchBox.DataContext = searchEngine;

请参阅here

答案 1 :(得分:0)

您必须在xaml中使用updatesourcetrigger,如:

<TextBox x:Name="SearchBox" Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged"/>