【问题标题】:Prevent infinite loop due "PropertyChanged - events" [duplicate]防止由于“PropertyChanged - 事件”而导致的无限循环 [重复]
【发布时间】:2020-12-26 14:54:48
【问题描述】:

我陷入了无限循环,我认为问题出在 XAML TextBox 中的 UpdateSourceTrigger=PropertyChanged。 我想要实现的是:

  • 我有 3 个文本框:
  • 1 -> 输入一个浮点数,这会在文本框 2(大端)和文本框 3(小端)中触发转换为十六进制值。
  • 2 -> 在文本框 2 中输入一个十六进制值,这会触发转换为在文本框 1 中浮动和在文本框 3 中等效的小尾数
  • 3 -> 相同的行为。

但我的问题是 UpdateSourceTrigger=PropertyChanged 触发了一系列导致我的应用程序无限循环或崩溃的事件。

我的 XAML 代码(查看):

<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBox
            Grid.Row="0"
            Grid.Column="0"
            Margin="5,0,5,0"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Bottom"
            CaretBrush="#FF202020"
            SelectionBrush="#FF202020"
            Text="{Binding FloatInput, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" />
        <TextBox
            Grid.Row="0"
            Grid.Column="1"
            Margin="5,0,5,0"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Bottom"
            CaretBrush="#FF202020"
            SelectionBrush="#FF202020"
            Text="{Binding HartInput, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" />
        <TextBox
            Grid.Row="0"
            Grid.Column="2"
            Margin="5,0,5,0"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Bottom"
            CaretBrush="#FF202020"
            SelectionBrush="#FF202020"
            Text="{Binding GDCInput}" />
    </Grid>

我的 VieModel 代码:

public class FloatHartGdcConverterViewModel: FoundationViewModel
    {

        private string _floatInput;

        public string FloatInput
        {
            get { return _floatInput; }
            set
            {
                _floatInput = value;
                //HartInput = GeneralConverters.HexaToFloat(_floatInput);
                OnPropertyChanged();
            }
        }

        private string _hartInput;

        public string HartInput
        {
            get { return _hartInput; }
            set
            {
                _hartInput = value;
                // FloatInput = GeneralConverters.FloatToHexa(_hartInput);
                OnPropertyChanged();
            }
        }

        private string _gdcInput;

        public string GDCInput
        {
            get { return _gdcInput; }
            set { _gdcInput = value; }
        }

    }

【问题讨论】:

  • 放置一些类级别的布尔值来控制事件处理程序是否应该提前退出

标签: c# xaml mvvm


【解决方案1】:

由于您在同一个班级,您可以直接将其写入“_”私有值,然后抛出您的 OnPropertyChanged()。由于您没有应用到 SETTER 组件,因此它不会递归调用其他组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2013-12-20
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多