XAML 使用NotificationBase时出现数据绑定问题

juzqafwq  于 2022-12-07  发布在  其他
关注(0)|答案(3)|浏览(109)
Custom_View.xaml

    <UserControl>
        <local:Custom_Text_Field
            Custom_Text_Field_Color="{x:Bind ViewModel.Color1 , Mode=TwoWay}">
        </local:Custom_Text_Field>
        <local:Custom_Text_Field
            Custom_Text_Field_Color="{x:Bind ViewModel.Color2 , Mode=TwoWay}">
        </local:Custom_Text_Field>
        <Button Click="{x:Bind ViewModel.ChangeColor"/>
    </UserControl>

Custom_View.cs

    public sealed partial class Custom_View : UserControl
    {
        public Custom_View_VM ViewModel { get; set; }
        public Custom_View()
        {
            ViewModel = new Custom_View_VM();
            this.InitializeComponent();
        }
    }

Custom_View_VM.cs

    public class Custom_View_VM : NotificationBase
    {
        public Brush Color1 { get; set; }
        public Brush Color2 { get; set; }
        public void  ChangeColor{//change color1 or color2};
    }

我使用了这个示例中的NotificationBase类:https://blogs.msdn.microsoft.com/johnshews_blog/2015/09/09/a-minimal-mvvm-uwp-app/
如果我在constructeur中影响Color1或Color2的值,它会起作用(更改视图),但在调用ChangeColor后,View模型中的值会更改,但不会影响视图。

68de4m5k

68de4m5k1#

若要更新UI,它应该接收PropertyChanged事件。您应该使用NotificationBase的机制来设定属性,这些属性也会引发PropertyChanged事件:

public class Custom_View_VM : NotificationBase
{
    private Brush color1;
    public Brush Color1 
    {
        get { return color1; }
        set { SetProperty(color1, value, () => color1 = value); }
    }
    // TODO: same here
    public Brush Color2 { get; set; }
    public void  ChangeColor{//change color1 or color2};
}

ViewModel应该有一些业务逻辑属性,你可以基于XAMLTextBox的颜色,比如IsNameAvailable

rxztt3cl

rxztt3cl2#

您需要注册该房产。

public static readonly DependencyProperty Custom_Text_Field_Color_Property =
        DependencyProperty.Register("Custom_Text_Field_Color", typeof(Brush), 
        typeof(Class_Name), new UIPropertyMetadata(null));

        public Brush Custom_Text_Field_Color
        {
            get { return (Brush)GetValue(Custom_Text_Field_Color_Property); }
            set { SetValue(Custom_Text_Field_Color_Property, value); }
        }

使用**typeof(Class_Name)**的控件名称(即类名)。

cfh9epnr

cfh9epnr3#

如果类NotificationBase是自定义类,则可以使用is或not。
我只对MVVM设计模式做了基本的说明,在ViewModel中,应该实现接口INotifyPropertyChanged,并且在设置属性时,触发事件PropertyChanged。

public sealed class MainPageViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _productName;
    public string ProductName
    {
        get { return _productName; }
        set
        {
            _productName = value;
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(ProductName)));
            }
        }
    }
}

下面的示例将演示此MVVM设计模式。https://code.msdn.microsoft.com/How-to-achieve-MVVM-design-2bb5a580

相关问题