[英]How to bind a child `UserControl`'s Dependency Property, using `Style`, to a property of the host element's view-model?
[英]How do you bind to a property in a xaml code-behind if the usercontrol's datacontext is a view-model?
我有一個UserControl,其DataContext被設置為ViewModel的實例(使用MVVM)。 但是,我在UserControl中有一些控件,這些控件需要綁定到僅與視圖有關的屬性(這就是為什么將它們放在代碼后面的原因)。 我不確定如何在xaml中適當地綁定它:
注意: SelectedOrderType
是視圖模型的屬性,而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上簡單地創建一個屬性,並且有人認為這是放置它的正確位置……但是我真的很想知道我該怎么做。我是否正在嘗試是否針對這種情況,也許將來針對其他情況?
我可能是錯的,但是您是否不需要在用戶控件上為“ SelectedOrderType”創建依賴項屬性,並將視圖模型綁定到該屬性,而不是直接從用戶控件綁定到視圖模型。
這樣,您的UserControl不依賴於視圖模型嗎?
編輯:
我認為您可以按照自己的方式進行設置,但是SelectedOrderType的綁定需要類似於{Binding Path = DataContext.SelectedOrderType,ElementName = OrderUserControl}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.