WPF:如何在嵌套的usercontrol中访问observablecollection?

时间:2016-02-19 06:03:46

标签: c# wpf user-controls observablecollection

在我的应用程序中我使用了两个usercontrol:UserControl1是主要的一个,在它里面,我有六次使用UserControl2。

UserControl2有几个组合框,我想从最终的应用程序中动态填充它们。首先,我试图将数据绑定到其中一个。

UserControl2中的组合框如下所示:

 <ComboBox x:Name="VidTransform" Template="{DynamicResource BaseComboBoxStyle}" ItemContainerStyle="{DynamicResource BaseComboBoxItemStyle}" Grid.Row="1" ItemsSource="{Binding Path=DataContext.VidTransformsNames,ElementName=Ch_Parameters, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedValue="{Binding Path=SelectedTransform,ElementName=Ch_Parameters, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

目前我只能手动填充它,使用此ObservableCollection(所有字符串都正确显示):

    private ObservableCollection<string> _VidTransformsNames = new ObservableCollection<string>(new[] { "test0", "test1", "test2", "test3", "test4", "test5" });
    public ObservableCollection<string> VidTransformsNames
    {
        get { return _VidTransformsNames; }
        set { _VidTransformsNames = value; }
    }

在UserControl1(包含UserControl2)中,我尝试创建另一个ObservableCollection并在运行时在我的最终应用程序中动态填充它。

这是:

    private ObservableCollection<string> _VideoTransformsNames = new ObservableCollection<string>(new[] { "Test0", "Test1", "Test2", "Test3", "Test4", "Test5" });
    public ObservableCollection<string> VideoTransformsNames
    {
        get { return _VideoTransformsNames; }
        set { _VideoTransformsNames = value; }
    }

然后绑定:

<local:UserControl1 VidTransformsNames="{Binding Path=VideoTransformsNames, ElementName=cmix, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

我是初学者,但在这里我肯定是错的,因为我收到了这个错误:

  

无法在“UserControl1”类型的“VidTransformsNames”属性上设置“绑定”。 '绑定'只能在DependencyObject的DependencyProperty上设置。

如果UserControl2嵌套在UserControl1中,如何在运行时访问并填充UserControl2的observablecollection?

1 个答案:

答案 0 :(得分:1)

这是因为您的属性需要正确声明为DependencyProperty

  

依赖项属性和WPF属性系统扩展属性   通过提供支持属性的类型的功能,作为   支持标准模式的替代实现   带私人场地的酒店。这种类型的名称是   的DependencyProperty。定义WPF的另一种重要类型   属性系统是DependencyObject。 DependencyObject定义基础   可以注册并拥有依赖属性的类。

请遵循此https://msdn.microsoft.com/library/ms753358(v=vs.100).aspx或相关属性概述https://msdn.microsoft.com/pl-pl/library/ms752914(v=vs.100).aspx

取自上述文章的例子:

public static readonly DependencyProperty IsSpinningProperty = 
    DependencyProperty.Register(
    "IsSpinning", typeof(Boolean),


...


    );
public bool IsSpinning
{
    get { return (bool)GetValue(IsSpinningProperty); }
    set { SetValue(IsSpinningProperty, value); }
}

让我们尝试将其设置为您的代码:

public static readonly DependencyProperty VideoTransformsNamesProperty = 
DependencyProperty.Register("VideoTransformsNames", typeof(ObservableCollection<string>), typeof(UserControl1));

public string VideoTransformsNames
{
    get
    {
        return this.GetValue(VideoTransformsNamesProperty) as ObservableCollection<string>;
    }
    set
    {
        this.SetValue(VideoTransformsNamesProperty, value);
    }
}
相关问题