在我的应用程序中,我使用了两个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'属性上设置'Binding'。只能在DependencyObject的DependencyProperty上设置“绑定”。
如果嵌套在UserControl1中,则如何在运行时访问和填充UserControl2的observablecollection?
这是因为您的财产需要正确声明为 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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句