我的应用中的多个视图包含ListView
,它们之间的差异为ItemsSource
,ListView
也绑定了一些命令,命令的实现在视图模型中是相同的。我想创建一个UserControl
并在用户控件的视图模型中处理该命令,这可以删除多个视图视图模型中的大量代码。
我的UserControl
看起来像这样:
public partial class CustomListViewControl : UserControl
{
public static readonly DependencyProperty MyItemsSourceProperty = DependencyProperty.Register("MyItemsSource", typeof(IEnumerable),
typeof(CustomListViewControl));
public CustomListViewControl()
{
InitializeComponent();
}
public IEnumerable MyItemsSource
{
get { return (IEnumerable)GetValue(CustomListViewControl.MyItemsSourceProperty); }
set { SetValue(CustomListViewControl.MyItemsSourceProperty, value); }
}
}
但是在命令中,我需要使用ItemsSource
。如何在DependencyProperty
的视图模型中将ObservableCollection<T>
挂钩到UserControl
?
答案 0 :(得分:0)
您需要为iCommand参数以及icommand本身公开依赖项属性
/// <summary>
/// BUTTON COMMAND: The iCommand of the button
/// </summary>
/// <remarks></remarks>
public ICommand ButtonCommand {
get { return GetValue(ButtonCommandProperty); }
set { SetValue(ButtonCommandProperty, value); }
}
public static readonly DependencyProperty ButtonCommandProperty = DependencyProperty.Register("ButtonCommand", typeof(ICommand), typeof(CustomListViewControl ), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
/// <summary>
/// BUTTON COMMAND: The iCommandParameter of the button
/// </summary>
/// <remarks></remarks>
public ObservableCollection<T> ButtonCommandParameter {
get { return GetValue(ButtonCommandParameterProperty); }
set { SetValue(ButtonCommandParameterProperty, value); }
}
public static readonly DependencyProperty ButtonCommandParameterProperty = DependencyProperty.Register("ButtonCommandParameter", typeof(ObservableCollection<T>), typeof(CustomListViewControl), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
现在您应该能够绑定到命令(此示例为ButtonCommand),然后将itemssource的listview的可观察集合绑定到ButtonCommandParamter。
我使用过这种方法,它在wpf 4.5中有用。我从VB转换,所以你可能需要稍微清理一下。
希望这有帮助。