假设我在具有 DependencyProperty 的控件的 DataContext 中有一个 ViewModel:
AControl.cs:
class AControl : Control /* could be another class e.g. Viewbox, Label */
{
public AControl()
{
DataContext = new AControlViewModel(/* this ?? */);
}
public int AProperty
{
get { return (int)GetValue(APropertyProperty); }
set { SetValue(APropertyProperty, value); }
}
public static readonly DependencyProperty APropertyProperty =
DependencyProperty.Register("AProperty", typeof(int),
typeof(AClass), new FrameworkPropertyMetadata(0));
}
AControlViewModel.cs:
class AControlViewModel : ViewModelBase
{
void SomeMethod()
{
// Some actions accessing AProperty for the Control
// in whose DataContext 'this' is in
}
// EDIT: Property added
private int vMProperty;
public int VMProperty
{
get { return vMProperty; }
set
{
if (vMProperty == value)
return;
vMProperty = value;
OnPropertyChanged("VMProperty"); // In ViewModelBase
}
}
}
我知道可以从 Control 传递 this-reference,但只能从代码隐藏传递。如何正确执行此操作(如果有比传递引用更简单的方法)以及如何从 Xaml 执行此操作?如果 AProperty 的值发生变化,如何获得通知?
编辑: 以另一个控件的样式:
<Style TargetType="{x:Type namespace:AnotherControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type namespace:AnotherControl}">
<Border>
<namespace:AControl AProperty="{TemplateBinding AnotherProperty}">
<!-- This Binding replaces the Binding 'AProperty="{Binding VMProperty}' inside AControl.
I think I have to bind to VMProperty instead of AProperty... but how?-->
</namespace:AControl>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>