C#WPF:依赖属性与MVVM
我需要创建一个具有Dependency属性的组件,我不知道如何绑定来自另一个用户控件的数据,有人能给我解释一下吗?我认为我不需要为组件创建viewmodel 这是我的代码: 这里我称之为组件C#WPF:依赖属性与MVVM,c#,wpf,mvvm,C#,Wpf,Mvvm,我需要创建一个具有Dependency属性的组件,我不知道如何绑定来自另一个用户控件的数据,有人能给我解释一下吗?我认为我不需要为组件创建viewmodel 这是我的代码: 这里我称之为组件 <DockPanel Grid.Row="1"> <ctrls:CustomComboBox Collection="{Binding Path=TestingCollection}" SelectedCollectionItem="{Binding Path=Se
<DockPanel Grid.Row="1">
<ctrls:CustomComboBox Collection="{Binding Path=TestingCollection}" SelectedCollectionItem="{Binding Path=SelectedItem}"
CreateCommand="" DeleteCommand="" UpdateCommand=""/>
</DockPanel>
这是我的组件
<ComboBox Grid.Column="0" SelectedValue="{Binding SelectedCollectionItem,ElementName=CustomComboBoxControl, Mode=TwoWay}"
ItemsSource="{Binding Collection}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
/>
这是我的xaml.cs
public static readonly DependencyProperty CollectionProperty =
DependencyProperty.Register("Collection", typeof(ObservableCollection<object>), typeof(CustomComboBox));
public ObservableCollection<object> Collection
{
get { return (ObservableCollection<object>)GetValue(CollectionProperty); }
set { SetValue(CollectionProperty, value); }
}
public static readonly DependencyProperty SelectedCollectionItemProperty =
DependencyProperty.Register("SelectedCollectionItem", typeof(object), typeof(CustomComboBox));
public object SelectedCollectionItem
{
get { return (object)GetValue(SelectedCollectionItemProperty); }
set { SetValue(SelectedCollectionItemProperty, value); }
}
公共静态只读DependencyProperty CollectionProperty=
DependencyProperty.Register(“Collection”、typeof(ObservableCollection)、typeof(CustomComboBox));
公开收集
{
get{return(ObservableCollection)GetValue(CollectionProperty);}
set{SetValue(CollectionProperty,value);}
}
公共静态只读从属属性SelectedCollectionItemProperty=
DependencyProperty.Register(“SelectedCollectionItem”、typeof(object)、typeof(CustomComboBox));
公共对象SelectedCollectionItem
{
获取{return(object)GetValue(SelectedCollectionItemProperty);}
set{SetValue(SelectedCollectionItemProperty,value);}
}
编辑:
我试着创建一个虚拟机并设置数据上下文,但依赖属性似乎毫无意义
编辑2:
我成功了,我删除了我缺少的VM和ItemSource中的ElementName我成功了,我删除了我缺少的VM和ItemSource中的ElementName你为什么不从ComboBox派生?无论如何,当您在SelectedValue绑定上有
ElementName=CustomComboBoxControl
时,为什么不在ItemsSource绑定上呢?我会在代码部分添加3个按钮。我试图使它尽可能短。UserControls不需要私有视图模型。假设customComboxControl
是UserControl的x:Name
,那么在SelectedValue绑定中设置ElementName就可以了。对ItemsSource绑定执行相同的操作。或者,写入ItemsSource=“{Binding Collection,RelativeSource={RelativeSource ansestortype=UserControl}”
。