【问题标题】:set property of child control viewmodel, from the parent view xaml从父视图 xaml 设置子控件视图模型的属性
【发布时间】:2014-10-02 09:09:01
【问题描述】:

我想从父视图 xaml 为子控件设置视图模型的属性。

所以我希望父 xaml 是这样的:

<UserControl x:Class="MainUserControl"
...>
<Grid...>
    <local:ChildDetailView x:Name="childView1" ChildVMProperty="ValueOptions.Option1"/>
    <local:ChildDetailView x:Name="childView2" ChildVMProperty="ValueOptions.Option2"/>
</Grid>
</UserControl>

ChildVMProperty 是 ChildDetailViewModel 上的一个属性(如果相关,则该属性采用 ValueOptions 类型的枚举)。

请注意,ViewModel 是在后面的代码中设置的(而不是在 xaml 中),因为实际上我在 ViewModel 中使用 DI 来注入 prism 事件聚合器。

当我尝试做这样的事情时,xaml 会抱怨,因为它显然对 ChildViewModel 类一无所知。执行此操作的正确语法是什么,或者如果它不那么直接,我必须有哪些选项来解决这个问题?

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    您需要先创建ChildDetailView.xaml 文件。假设您将此文件放在命名空间MyApp.Controls 中,那么您上面的 XAML 将类似于

    <UserControl x:Class="MainUserControl"
                 xmlns:local="clr-namespace:MyApp.Controls" >
        <Grid ...>
            <local:ChildDetailView x:Name="childView1" ChildVMProperty="ValueOptions.Option1"/>
            <local:ChildDetailView x:Name="childView2" ChildVMProperty="ValueOptions.Option2"/>
        </Grid>
    </UserControl>
    

    您必须确保在您的UserControl 上也定义了DependencyProperty (DP) ChildVMProperty - 但这是另一个问题,关于该特定主题有很多答案。要为视图添加 DP,您可能需要对您尝试定位的特定控件进行子类化。

    对属性使用 DP 的另一种替代方法是使用转换器。

    我希望这会有所帮助。

    【讨论】:

    • 谢谢。如果给子View添加一个DP,子ViewModel怎么知道值是什么? (需要使用该值的是子 ViewModel)
    • 通过绑定到 DP。 ChildVMProperty={Binding PropertyInTheViewModel}.
    • 如果我绑定属性,那么我无法在 xaml.xml 中实际设置值。我研究过 OneWayToSource 绑定,但无法弄清楚如何指定值(TargetNullValue 不起作用)。
    猜你喜欢
    • 2018-05-19
    • 1970-01-01
    • 2013-05-11
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多