我正在重构我之前写的一段代码。我编写了一个自定义用户控件,该控件允许用户选择一个对应对象。

viewmodel具有2个定义为

#region Properties
[ViewToViewModel(MappingType = ViewToViewModelMappingType.TwoWayViewWins)]
public bool AllowNull
{
    get { return (bool)GetValue(AllowNullProperty); }
    set { SetValue(AllowNullProperty, value); }
}
public static readonly DependencyProperty AllowNullProperty = DependencyProperty.Register("AllowNull", typeof(bool),
    typeof(CounterpartChooserControl), new PropertyMetadata(default(bool)));


/// <summary>
/// This Dependency property is used upon KeyDown to propagate the click to the target usercontrol
/// </summary>
public ICommandSource DestinationControl
{
    get { return (ICommandSource)GetValue(DestinationControlProperty); }
    set { SetValue(DestinationControlProperty, value); }
}

public static readonly DependencyProperty DestinationControlProperty = DependencyProperty.Register("DestinationControl", typeof(ICommandSource), typeof(CounterpartChooserControl),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None));
#endregion

在 View 中,我需要使用它,因为
  <views4:CounterpartChooserControl Grid.Row="9" Grid.Column="1" Margin="5,2,5,2" DataContext="{Binding CounterPartModel}" >
        </views4:CounterpartChooserControl>

这意味着我在viewmodel中有一个属性定义为
[ViewModelToModel("Model")]
public CounterPartModel CounterPartModel
{
    get { return GetValue<CounterPartModel>(CounterPartModelProperty); }
    set { SetValue(CounterPartModelProperty, value); }
}

public static readonly PropertyData CounterPartModelProperty = RegisterProperty("CounterPartModel", typeof(CounterPartModel), null);

我现在面临的问题是,更改SelectedItem(在CounterpartChooserViewModel中定义)后,此信息不会直接传播到主 View 模型(这是合理的,因为它位于 View 模型内部,因此不会通知嵌套属性在主 View 模型中)。

这样可以吗,还是我应该在主viwemodel中有一个SelectedCounterpart,通过XAML将其绑定(bind)为



并通过 View 本身以某种方式解决了数据上下文?

最佳答案

由于并非所有上下文都可用,因此我将在这里和那里假设一些事情。

可以,因为您实际上是在子虚拟机内部处理模型。子虚拟机仅知道其具有的模型(CounterPartModel)。如果引用相同,则您在子虚拟机内部对模型所做的更改应直接在主虚拟机中可见。

否则,您必须建立某种形式的通信(消息传递,服务,感兴趣等),以将更改通知其他虚拟机。

关于c# - 最佳实践是使用模型还是简单属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32839144/

10-17 02:34