用户控件的依赖属性中UWP属性变化

3

我是使用用户控件,并绑定依赖属性的值。 但问题在于,当我尝试更改该值时,界面不会更新。 我的用户控件 XAML 代码:

<TextBox Text="{x:Bind Text}" />

以及C#

 public event PropertyChangedEventHandler PropertyChanged;


    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value);
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                    new PropertyChangedEventArgs("Text"));
            }
        }
    }

    // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(Control1), new PropertyMetadata(null));

当我想要使用它时:
        <local:Control text="{Binding Val,Mode=TwoWay}" />

我的视图模型:

public event PropertyChangedEventHandler PropertyChanged;
    private string _val;
    public string Val
    {
        get
        {
            return _val;
        }

        set
        {

            if (_val != value)
            {_val = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this,
                        new PropertyChangedEventArgs("Val"));
                }
            }
        }

    }

当我想在视图中使用它并从视图模型中绑定时,属性更改不会应用于用户控件。

1个回答

4
< p > 对于 < code > x:bind ,默认模式是 One Time,你应该将模式更改为 OneWay。 < /p >
<TextBox Text="{x:Bind Text,Mode=OneWay}" />

你不应该在 SetValue(TextProperty, value); 中编写代码,也不应该在依赖属性中使用Notify,因为依赖项可以自动调用更改。
参见:依赖属性

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接