首页 > 解决方案 > 不为 textchanged 命令调用 WPF 多转换器

问题描述

我有一个如下所示的 WPF UI。它有一个包含所有项目的组合框,每个项目包含 2 个段。段视图放置在不同的内容控件上。每个段视图都有一个复选框来启用/禁用整个段的内容。

我在段视图中的绑定

<TextBox Grid.Row="0" Grid.Column="1" Name="leftDistanceTextBox" 
                     Text="{Binding LeftDistance, UpdateSourceTrigger=PropertyChanged}">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="TextChanged">
                        <i:InvokeCommandAction Command="{Binding DistanceChangedCommand}">
                            <i:InvokeCommandAction.CommandParameter>
                                <MultiBinding Converter="{StaticResource BeamIntersectionMultiConverter}" ConverterParameter="true">
                                    <Binding ElementName="leftDistanceTextBox"/>
                                    <Binding ElementName="enabledCheckBox"/>
                                </MultiBinding>
                            </i:InvokeCommandAction.CommandParameter>
                        </i:InvokeCommandAction>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </TextBox>

我的转换器

 public class BeamIntersectionParamMultiConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            // it never stops here in debug mode, except the initializtion
            Debugger.Break();
            if (Validate(values, parameter))
            {
                TextBox control = values[0] as TextBox;

                CheckBox activation = values[1] as CheckBox;
                bool isEnabled = activation.IsChecked == true ? true : false;

                string text = (string)parameter;
                bool.TryParse(text, out bool isLeft);

                return new BeamIntersectionParam(control, isEnabled, isLeft);
            }
            return null;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return null;
        }


问题是:我想通过 interation.Command 验证/更新视图模型。该命令有一个 MultiBindnig,其中一个绑定到当前文本框,另一个绑定到提到的 CheckBox。但是,传递给被调用方法的参数仅具有组合框中第一项的初始状态(尽管 TextBox 的内容是最新的)。后来,我在调试模式下将 Debugger.Break() 添加到我的转换器中,发现在视图初始化期间只调用了一次转换器。

如果我的转换器只调用一次,为什么我会在调用方法中获取绑定文本框的最新内容?

如果每次都调用它,为什么代码不会在转换器调试模式内停止?

发生了什么以及如何解决?非常感谢大家。

P/s:我很抱歉,因为英语不是我的母语。如果您需要更多信息,请询问。

标签: c#wpfconverters

解决方案


看起来这是因为您绑定到CheckBox控件本身(除非在初始化时加载它,否则它不会“更改”),而不是它的IsChecked属性。

执行以下工作(注意:您必须更改转换器,因为它将接收 type 的值bool,而不是 type CheckBox):

<Binding ElementName="leftDistanceTextBox"/>
<Binding Path="IsChecked", ElementName="enabledCheckBox" />
<Binding Path="Text", ElementName="leftDistanceTextBox"/>

推荐阅读