Binding usercontrol property to custom class

后端 未结 1 507
悲&欢浪女
悲&欢浪女 2020-12-07 06:29

In my application I\'m using a usercontrol called \"ChannelControls\" which I instance 6 times, on the mainwindow.

public partial class Channel         


        
1条回答
  •  既然无缘
    2020-12-07 07:15

    A UserControl should never have an "own" instance of a view model. Instead, it should have dependency properties that are bound to properties of an "external" view model.

    Your ChannelsControl would declare a property like this (where I suppose that string is not an appropriate type for a count):

    public partial class ChannelsControl : UserControl
    {
        public static readonly DependencyProperty SpriteCountProperty =
            DependencyProperty.Register(
                nameof(SpriteCount), typeof(string), typeof(ChannelsControl));
    
        public string SpriteCount
        {
            get { return (string)GetValue(SpriteCountProperty); }
            set { SetValue(SpriteCountProperty, value); }
        }
    
        ...
    }
    

    In ChannelsControl's XAML, you would bind it like this:

    
    

    You would now use your UserControl like shown below, where you bind the Count property to a view model in the DataContext like this:

    
        
    
    ...
    
    
    

    You may now also use ChannelsControl in the ItemTemplate of an ItemsControl like this:

    
        
            
                
            
        
    
    

    EDIT: Set the Window's DataContext to your view model singleton instance like this:

    
    

    Or in code behind, in the MainWindow constructor:

    DataContext = CMiXData.Instance;
    

    0 讨论(0)
提交回复
热议问题