简体   繁体   English

如何使C#用户控件属性数据可绑定?

[英]How do I make a C# user control property data bindable?

I have a MVVM Windows Phone 8 app. 我有一个MVVM Windows Phone 8应用程序。 The XAML page has a user control that I created that needs to be notified when a change takes place in the View Model . XAML页面具有我创建的用户控件 ,在视图模型中发生更改时需要通知该控件 To facilitate this, I created an int property in the user control to be bound to a property in the View Model , so the user control property's setter method would be triggered when the property it was bound to in the View Model changed. 为方便起见,我在用户控件中创建了一个int属性以绑定到View Model中的一个属性,因此,当在View Model中绑定到该控件的属性时,将触发该用户控件属性的setter方法。

Using the code below, the user control's VideosShownCount property does show up in the Property List at design-time but when I click on the binding mini-button, the Create Data Binding option is greyed out in the pop-up menu. 使用下面的代码, 用户控件的 VideosShownCount属性确实在设计时显示在“ 属性列表”中 ,但是当我单击绑定微型按钮时,弹出菜单中的“ 创建数据绑定”选项显示灰色

So I have one or two questions, depending on what is the root problem: 所以我有一个或两个问题,这取决于根本问题是什么:

1) How do I make a property in a View Model available as a Data Binding source? 1)如何使视图模型中的属性可用作数据绑定源?

2) How do I format a user control property so the IDE allows it to be data bound to a View Model property? 2)如何格式化用户控件属性,以便IDE允许将其绑定到视图模型属性的数据?

    private int _videosShownCount = 0;

    public int VideosShownCount 
    { 
        get
        {
            return this._videosShownCount;
        }
        set
        {
            this._videosShownCount = value;
        }
    }

    public static readonly DependencyProperty VideoShownCountProperty =
        DependencyProperty.Register("VideosShownCount", typeof(int), typeof(MyUserControl), 
        new PropertyMetadata(0, new PropertyChangedCallback(VideoShownCountPropertyChanged))); 

    static void VideoShownCountPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MyUserControl MyUserUserControl = (MyUserControl)sender;

        // Don't care about the value, just want the notification.
        // int val = (int)e.NewValue;

        // Do work now that we've been notified of a change.
        MyUserUserControl.DoWork();
    }

You're not using the DependencyProperty for your property, which will definitely cause problems between your code and the bindings 您没有为属性使用DependencyProperty ,这肯定会导致代码与绑定之间出现问题

public int VideosShownCount
{
    get { return (int) GetValue(VideosShownCountProperty); }
    set { SetValue(VideosShownCountProperty, value); }
}

I'm not sure if this is the main cause of your problem, but it's worth fixing regardless. 我不确定这是否是造成问题的主要原因,但是无论如何都值得修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM