Coerce a WPF TextBox not working anymore in .NET 4.0

前端 未结 2 1532
小蘑菇
小蘑菇 2020-11-30 15:20

In my WPF application I have a TextBox where the user can enter a percentage (as int, between 1 and 100). The Text property is databound to a property in a ViewModel, where

相关标签:
2条回答
  • 2020-11-30 15:39

    Try using in xaml Explicit instead of PropertyChanged:

    <TextBox Text="{Binding Percentage, Mode=TwoWay, UpdateSourceTrigger=Explicit, TargetNullValue={x:Static System:String.Empty}}"
                 TextChanged="TextBox_TextChanged" />
    

    and in code behind UpdateSource instead of UpdateTarget

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // Removed safe casts and null checks
            ((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }
    

    Tested it and it works. Btw this problem will probably be resolved in a later version of .NET.

    0 讨论(0)
  • 2020-11-30 15:57

    You can use PropertyChanged. However, try binding to the EditValueProperty dependency instead of the TextProperty dependency (or events). It will work as desired.

    0 讨论(0)
提交回复
热议问题