Binding usercontrol property to custom class

后端 未结 1 502
悲&欢浪女
悲&欢浪女 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:

    <CMiX:Counter Count="{Binding SpriteCount,
                          RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    

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

    <Window.DataContext>
        <local:CMiXData />
    </Window.DataContext>
    ...
    
    <local:ChannelsControl SpriteCount="{Binding SpriteCount[0]}" ... />
    

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

    <ItemsControl ItemsSource="{Binding SpriteCount}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <local:ChannelsControl SpriteCount="{Binding}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

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

    <Window ... DataContext="{x:Static local:CMiXData.Instance}" >
    

    Or in code behind, in the MainWindow constructor:

    DataContext = CMiXData.Instance;
    
    0 讨论(0)
提交回复
热议问题