如何将用户控件的某些属性绑定到ObservableCollection中的对象实例的某些属性?

时间:2019-07-03 04:22:42

标签: c# wpf

我有一个由文本块组成的用户控件TagUC,以便它可以在其中显示一些文本。 TagUC已绑定到ObservableCollection中的对象实例,如下所示:

MainWindow.xaml

<ItemsControl ItemsSource="{Binding Model1.OC1}">
        <ItemsControl.ItemsPanel>
              <ItemsPanelTemplate>
                     <WrapPanel x:Name="WP1" />
              </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
              <DataTemplate>
                     <uc:TagUC TagName="<!--WHAT SHOULD BE HERE-->"/>
              </DataTemplate>
        </ItemsControl.ItemTemplate>
</ItemsControl>

TagUC.xaml

<TextBlock Text="{Binding TagName}" />

TagUC.xaml.cs

public partial class TagUC: UserControl
{
        public TagUC()
        {
            InitializeComponent();
            this.DataContext = this;
        }
        public static readonly DependencyProperty TextBlockProperty = 
             DependencyProperty.Register("TagName", typeof(string), 
             typeof(TagUC), new PropertyMetadata(null));
        public string TagName
        {
            get
            {
                return (string)GetValue(TextBlockProperty);
            }
            set
            {
                SetValue(TextBlockProperty, value);
            }
        }
}

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    private MainWindowVM _VM = new MainWindowVM ();
    public MainWindowVM VM{ get { return _VM ; } set { _VM = value; } }
    public MainWindow()
    {
        this.DataContext = VM;
        InitializeComponent();
    }
   /* Some Other codes */
}

MainWindowVM由模型Model1组成:

MainWindowVM.cs

public class MainWindowVM
{
    private Model1 _md1 = new Model1 ();
    public Model1 MD1 { get { return _md1 ; } set { _md1 = value; } }

    /* Some Other codes */
}

Model1包含ObservableCollection,它由SomeObject的实例组成:

Model1.cs

public class Model1
{
    private ObservableCollection<SomeObject> _oC1 = new 
         ObservableCollection<SomeObject>();
    public ObservableCollection<SomeObject> OC1{ get { return _oC1 ; } set { 
         _oC1 = value; } }

    /* Some Other codes */
}

Text1是我要显示的TagName:

SomeObject.cs

public class SomeObject
{
    private string _text1;
    public string Text1 { get { return _text1; } set { _text1= value; } }

    /* Some Other codes */
}

MainWindow中“应该在这里”应该是什么?

0 个答案:

没有答案