简体   繁体   中英

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

I have a MVVM Windows Phone 8 app. The XAML page has a user control that I created that needs to be notified when a change takes place in the View Model . 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.

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.

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?

2) How do I format a user control property so the IDE allows it to be data bound to a View Model property?

    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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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