wpf - M-V-VM WPF : Way to maintain Databinding while passing parent object of Databound object into IValueConverter?

标签 wpf data-binding mvvm ivalueconverter

我正在使用 model-view-viewmodel 我目前有一个包含 3 条数据的类:2 个整数和一个枚举。

它的构造函数如下所示:

//C#
public Outcome(OutcomeEnum outcomeEnum, Int32 acutalOutcomeData, Int32 expectedOutcomeData)
{
  m_outcomeEnum = outcomeEnum;
  m_actualData = acutalOutcomeData;
  m_expectedData = expectedOutcomeData;
}

我有 2 个彼此相邻的组合框,我已绑定(bind)到一个结果对象列表( List<Outcome> ),我将其用于“实际”和“预期”整数值。

这部分代码如下所示:( SelectedItem 和 ItemsSource 是 viewmodel 中的依赖属性)
<ComboBox ItemsSource="{Binding Path=OutcomeList}" SelectedItem="{Binding SelectedExpectedOutcome, Mode=TwoWay}" x:Name="PART_cbExpectedOutcome" Grid.Column="1" >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Label Content="{Binding Path=ExpectedOutcomeData, Converter={StaticResource OutcomeDataToStringConverter}, ConverterParameter=Expected }" />  
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
<ComboBox ItemsSource="{Binding Path=OutcomeList}" SelectedItem="{Binding SelectedActualOutcome, Mode=TwoWay}" x:Name="PART_cbActualOutcome" Grid.Column="2" >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Label Content="{Binding Path=ActualOutcomeData, Converter={StaticResource OutcomeDataToStringConverter}, ConverterParameter=Actual}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我的问题是:我想将对 Outcome 对象的引用传递到我用来在其之间进行转换的 IValueConverter 中,但这似乎无法使用 IConvertParameter 而是我将被迫根据 msdn post here 使用 Multibinding .

我想将我的方法简化为为相对简单的东西创建多重绑定(bind),因为这看起来有点矫枉过正。

我只想对我试图传递给 IValueConverter 的 Outcome 对象做一件事,即确定 OutcomeEnum 的枚举类型,以便我可以提供预期或实际数据值的正确格式。

有没有更简单的方法可以将 Outcome 对象传递到 IValueConverter OutcomeDataToStringConverter 中,同时保持与这个 Outcome 对象列表的双向绑定(bind)?我愿意接受建议。

最佳答案

为什么不绑定(bind)到整个 Outcome对象而不是它的 ActualOutcomeDataExpectedOutcomeData特性?这样转换器将收到整个 Outcome对象,并基于它和转换器参数返回正确的值。

<ComboBox.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <Label Content="{Binding Converter={StaticResource OutcomeToStringConverter}, ConverterParameter=Expected}"/>
        </StackPanel>
    </DataTemplate>
</ComboBox.ItemTemplate>

关于wpf - M-V-VM WPF : Way to maintain Databinding while passing parent object of Databound object into IValueConverter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1949782/

相关文章:

javascript - 输入上的 v-model 返回输入元素而不是值

c# - 如何以Xamarin形式从CustomViewCell调用任何Navigation.PushPopupAsync?

android - 无法使用 Hilt 创建 MainViewModel 的实例

mysqli_stmt_bind_param 正在我的中插入零

c# - 虚拟机的 UWP MVVM 数据绑定(bind)(来自字符串的 textbox.text)

javascript - 更改自定义处理程序内可观察的模型

c# - 在WPF MVVM应用程序中添加 Material 设计后,数据网格不显示滚动条,并且设计变得过时

c# - 处理 WPF TextBox LostFocus 事件和绑定(bind)的顺序

WPF——为什么这个 EventTrigger 不起作用?

c# - 如何在WPF文本 block 验证错误上显示消息框