C# 自定义控件绑定
我有两个自定义控件,a和b 自定义控件C# 自定义控件绑定,c#,wpf,data-binding,wpf-controls,C#,Wpf,Data Binding,Wpf Controls,我有两个自定义控件,a和b 自定义控件a具有类型为aClass 自定义控件b上有一组a,并且有一个名为ItemSourceUI 还有另一个类bClass,它具有类型为aClass的可观察集合,这在我的视图模型上使用 public class MyViewModel : INotifyPropertyChanged { public MyViewModel() { MyBClassInstance = new bClass(); } private
a
具有类型为aClass
自定义控件b
上有一组a
,并且有一个名为ItemSourceUI
还有另一个类bClass
,它具有类型为aClass
的可观察集合,这在我的视图模型上使用
public class MyViewModel : INotifyPropertyChanged
{
public MyViewModel()
{
MyBClassInstance = new bClass();
}
private bClass _MyBClassInstance;
public bClass MyBClassInstance
{
get { return _MyBClassInstance; }
set { SetProperty(ref _MyBClassInstance, value); }
}
....
// Here Implement INotifyPropertyChanged
}
这是我的看法
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UILib="clr-namespace:Gramas.UI;assembly=Gramas" x:Class="MyProy.Views.myView"
Title="{Sample}" Height="600" Width="1200">
<Grid>
<UILIb:b Margin="10" ItemSourceUI="{Binding MyBClassInstance}"/>
</Grid>
</Window>
我的问题是ItemSourceUI
atb
自定义控件的依赖项属性设置器永远不会发生
我错过了什么
更新:这是b
public bClass ItemSourceUI
{
get { return (bClass)GetValue(ItemSourceUIProperty ); }
set
{
SetValue(ItemSourceUIProperty , value);
DataContext = value;
}
}
public static readonly DependencyProperty ItemSourceUIProperty =
DependencyProperty.Register("ItemSourceUI", typeof(bClass), typeof(b), new PropertyMetadata(default(bClass)));
此代码会导致您遇到的所有问题。您搞糟了DataContext,绑定需要适当的DataContext才能工作
public bClass ItemSourceUI
{
get { return (bClass)GetValue(ItemSourceUIProperty ); }
set
{
SetValue(ItemSourceUIProperty , value);
DataContext = value;
}
}
从setter中删除该DataContext,您应该不会有问题
如果您对此有任何疑问,请随时提问:)什么是“自定义控件b上有一组a”?什么是一套东西?事实上,你为什么还要告诉我们你的
aClass
?我在您的示例代码中没有看到这一点。您是否尝试过对您的ItemSourceUI
属性使用observateCollection
而不是列表
对不起,Sheridan,我正在尝试恢复一个对我来说实际上很复杂的问题。自定义控件b
上有20个a
类型的自定义控件实例,每个实例都需要一个aClass
作为控制源。但现在我的第一个问题是,我无法准确地在b
获取ItemSourceUI
。。。目前,您的aClass
与当前问题有些不相干,可能只是混淆了问题。能否回答您是否尝试对ItemSourceUI属性而不是列表使用ObservableCollection?aClass元素可能会随用户/程序交互而更改,我希望在UI上反映这些更改。这就是为什么“我认为”我需要一个可观察的集合。你忘了告诉我们你是如何定义你所说的依赖属性的。它的默认值是什么?因为您破坏了自己的DataContext。只要拆下那根线,它就会工作。好啊
public bClass ItemSourceUI
{
get { return (bClass)GetValue(ItemSourceUIProperty ); }
set
{
SetValue(ItemSourceUIProperty , value);
DataContext = value;
}
}