我需要翻译一个接收xaml参数的用户控件:
<components:MyComponent Sex="MALE"/>
在 MyComponent 控件中,我有一个绑定 ViewModel,如下所示:
<UserControl.DataContext>
<components:MyComponentViewModel/>
</UserControl.DataContext>
在MyComponent的代码后台中,看起来像这样:
public partial class MyComponent: UserControl
{
public string Sex
{
get => (string)GetValue(SexParamProperty);
set { SetValue(SexParamProperty, value); }
}
public static readonly DependencyProperty SexParamProperty = DependencyProperty.Register(nameof(Sex), typeof(string), typeof(MyComponent));
public MyComponent()
{
InitializeComponent();
}
}
我的组件视图模型长这样:
public class MyComponentViewModel: ViewModelBase
{
public string Sex { get; set; }
}
我希望ViewModel能够知道UserControl中性别(Sex)的值。这是否违背了MVVM模式,或者有一种尊重MVVM的方法可以做到这一点?我该如何实现?
Sex
的DP,必须命名为SexProperty
。如果DP命名为SexParamProperty
,则属性必须命名为SexParam
。然后您可以将其绑定为Sex="{Binding SexInVM}"
,其中SexInVM
是外部ViewModel的属性。 - undefinedMyComponentViewModel
。 - undefined