【发布时间】:2014-03-31 14:19:26
【问题描述】:
我有一个 UserControl,它的 DataContext 被设置为 ViewModel 的一个实例(使用 MVVM)。但是,我在 UserControl 中有控件,这些控件需要绑定到仅与视图相关的属性(这就是我将它们放在代码后面的原因)。我不确定如何在 xaml 中适当地绑定它:
注意:SelectedOrderType 是 View-Model 的属性,OrderTypes 是 UserControl 本身的属性。
<UserControl x:Class="MyNamespace.OrderControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="OrderUserControl">
<Grid>
...
<ComboBox ItemsSource="{Binding Path=OrderTypes, ElementName=OrderUserControl}"
SelectedValue="{Binding Path=SelectedOrderType}"
SelectedValuePath="OrderTypeCode"
DisplayMemberPath="OrderTypeName" />
</Grid>
</UserControl>
public partial class OrderControl : UserControl
{
public OrderControl()
{
InitializeComponent();
OrderTypes = ...;
}
public IReadOnlyCollection<OrderTypeInfo> OrderTypes { get; private set; }
}
另外,我知道我可以简单地在 View-Model 上创建一个属性,并且我知道有些人会建议将其放置在正确的位置...但我真的很想知道如何才能如果不是为了这个场景,也许在未来的其他场景中,做我正在尝试做的事情?
【问题讨论】:
标签: c# wpf xaml mvvm user-controls