我有一个名为LoggingControl的用户Control,它具有名为ParentID和DocumentType的依赖项属性。
我在另一个父级用户控件中使用了用户控件作为子控件。
<Grid Grid.Row="2" HorizontalAlignment="Center">
<Local:LoggingControl
ParentID="{Binding Path=DataContext.SelectedCRM_T001A.CatNo,
Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,
RelativeSource={RelativeSource
AncestorType={x:Type Local:WindowElement}}}" >
</Local:LoggingControl>
</Grid>
依赖属性:
public partial class LoggingControl : UserControl
{
public LoggingControl()
{
InitializeComponent();
this.DataContext = new COM_T002_VM();
}
public static readonly DependencyProperty ParentIDProperty =
DependencyProperty.Register("ParentID", typeof(int?), typeof(LoggingControl),
new PropertyMetadata(0));
public int? ParentID
{
get { return GetValue(ParentIDProperty) as int?; }
set
{
SetValue(ParentIDProperty, value);
}
}
}
我希望在我的View Model中访问我的依赖项属性(即COM_T002_VM)。如何将它们绑定在一起,以便我们可以在ViewModel中随时更改它们?
答案 0 :(得分:2)
如果您创建&#34;真实&#34;具有依赖属性的UserControls你应该从不:
this.DataContext = new COM_T002_VM();
这打破了Datacontext的继承!
你应该做的是某种相对绑定(ElementName或RelativeSource):
<UserControl x:Name="myLoggingUc">
...
<!-- you always bind in your UserControl to the DPs! -->
<TextBox Text="{Binding ElementName=myLoggingUc, Path=ParentID, Mode=TwoWay}" />
在外面的任何地方使用:
<Grid Grid.Row="2" HorizontalAlignment="Center">
<!-- the DataContext here should be your Viewmodel with a Property SelectedCRM_T001A -->
<!-- And this Property should have a Property CatNo, now its working-->
<Local:LoggingControl ParentID="{Binding Path=SelectedCRM_T001A.CatNo,Mode=TwoWay}" />
</Grid>