小编Mat*_*och的帖子

带有自定义依赖项属性的UserControl问题

我正在为一个名为SearchText的搜索文本编写一个带依赖项属性的用户控件.它是一个依赖属性,因为我想允许控件的使用者使用数据绑定.用户控件包含WPF TextBox,用户可以在其中输入搜索文本.

我可以使用数据绑定将用户控件的SearchText依赖项属性与TextBox的Text依赖项属性相连接,但此绑定仅在文本框丢失输入焦点时触发.我想要的是每次更改文本后都要更新的SearchText.所以我在用户控件中添加了一个TextChanged事件处理程序,我在其中将SearchText设置为Text的值.

我的问题是,SearchText绑定不起作用,源永远不会更新.我究竟做错了什么?

这是用户控件代码隐藏的相关部分:

public partial class UserControlSearchTextBox : UserControl
{
    public string SearchText
    {
        get { return (string)GetValue(SearchTextProperty); }
        set { SetValue(SearchTextProperty, value); }
    }

    public static readonly DependencyProperty SearchTextProperty =
        DependencyProperty.Register("SearchText", typeof(string), typeof(UserControlSearchTextBox), new UIPropertyMetadata(""));

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        SearchText = ((TextBox)sender).Text;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

包含用户控件实例的窗口将其DataContext设置为具有也称为SearchText的属性的对象.

<uc:UserControlSearchTextBox SearchText="{Binding SearchText}" />
Run Code Online (Sandbox Code Playgroud)

Window的数据上下文:

public class DataSourceUserManual : DataSourceBase
{
    private string _searchText;
    public string SearchText
    {
        get { return _searchText; }
        set
        {
            _searchText = value; …
Run Code Online (Sandbox Code Playgroud)

c# data-binding wpf dependencies properties

5
推荐指数
1
解决办法
3220
查看次数

标签 统计

c# ×1

data-binding ×1

dependencies ×1

properties ×1

wpf ×1