wpf 多重绑定到视图模型? [英] wpf multibinding to viewmodel?

查看:67
本文介绍了wpf 多重绑定到视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的一生,我似乎无法使用多重绑定绑定到我的视图模型.网络上的所有示例都直接绑定到 gui 元素,但是每当我尝试使用 viewmodel 对象时,都会抛出异常.

For the life of me, I can't seem to bind to my viewmodel using multibindings. All of the examples on the net bind to gui elements directly, but whenever I try with a viewmodel object exceptions are thrown.

我的问题是,如何向 xaml 中的多个视图模型对象添加多重绑定?

My question is, how do I add a multibinding to several viewmodel objects in xaml?

我需要将上下文菜单的 IsEnabled 属性绑定到我的视图模型中的两个整数.以下绑定不起作用,因为它是为 GUI 组件设计的.我将如何处理我的整数?

I need to bind the IsEnabled property of a context menu to two integers in my viewmodel. The following binding doesn't work, since its designed for GUI components. How would I do it to work with my ints?

<MenuItem ItemsSource="{Binding MyMenuItem}">
    <MenuItem.IsEnabled>
        <MultiBinding>
            <Binding ElementName="FirstInt" Path="Value" />
            <Binding ElementName="SecondInt" Path="Value" />
        </MultiBinding>
    </MenuItem.IsEnabled>
</MenuItem>

MyMenuItem 是包含两个整数 FirstInt 和 SecondInt 的 CLR 对象.

MyMenuItem is CLR object with the two integers, FirstInt and SecondInt.

推荐答案

Filip 的回答是可以接受的,但对于任何寻找 Filip 所需解决方案的人来说,应该这样做:

Filip's answer was acceptable, but for anyone looking for Filip's desired solution, the following should do it:

<MenuItem ItemsSource="{Binding MyMenuItem}">
    <MenuItem.IsEnabled>
        <MultiBinding  Converter="{StaticResource IntsToEnabledConverter}">
            <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="DataContext.FirstInt" />
            <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="DataContext.SecondInt" />
        </MultiBinding>
    </MenuItem.IsEnabled>
</MenuItem>

需要注意的是绑定上的AncestorType可能需要做相应的修改.我假设视图模型被设置为窗口的 DataContext,但同样的想法也适用于用户控件等.

It should be noted that the AncestorType on the binding may need to be changed accordingly. I assumed the view model was set as the DataContext of the window, but the same idea applies to user controls, etc.

这篇关于wpf 多重绑定到视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆