【问题标题】:UWP property changed in dependency property of user control用户控件的依赖属性中的 UWP 属性已更改
【发布时间】:2017-04-28 04:03:50
【问题描述】:

我正在使用用户控件,从依赖属性绑定值。 但问题是,当我尝试更改值时,UI 不会更新。 我在用户控件中的 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"));
                }
            }
        }

    }

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

【问题讨论】:

    标签: mvvm uwp dependency-properties


    【解决方案1】:

    对于x:bind,默认模式是一次,您应该将模式更改为 OneWay。

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

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

    见:Dependency Properties

    【讨论】:

      猜你喜欢
      • 2015-12-05
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多