弹出式文本框双向绑定

4

我试图在一个弹出框中设置文本框的绑定文本,但是我的视图模型的绑定属性的setter从未被调用。我将视图设置如下:

<CommandBar>
   <AppBarButton Icon="Edit" AllowFocusOnInteraction="true">
      <Flyout>
         <StackPanel>
            <TextBlock Text="Enter Qty:" />
            <TextBox Text="{Binding EditQty, Mode=TwoWay}" InputScope="Number" />
            <Button Content="Update" Command="{Binding EditCommand}" />
         </StackPanel>
      </Flyout>
<CommandBar>

我的 ViewModel 代码也很简单:

public decimal _editQty;
public decimal EditQty
{
    get => _editQty;
    set => Set(ref _editQty, value);
}

我甚至尝试使用UpdateSourceTrigger=Explicit绑定数据,然后在按钮的点击事件中,设置代码后台调用。

textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();

在调试期间,我可以看到textBox.Text的值已经正确更改,但是setter仍然没有被UpdateSource()调用。如果这很重要,我正在使用Windows 10 Build 14393(周年纪念版)。
有什么办法可以解决吗?此时,我将不得不放弃这个想法,并将文本框放在对话框中,即使将其放在flyout中会带来更好的用户体验。

启动时是否调用了getter方法? - Sean O'Neil
当弹出窗口打开时,getter 被调用。 - Rkand
2个回答

4
根据Microsoft的说法,自WinRT时代以来,UWP就无法进行十进制的双向绑定!(原因是:不要问!)他们的解决方案是使用浮点数。
如果您确实需要绑定到十进制数,似乎可以使用IValueConveter手动转换(感谢Stephan Olson,其解决方案链接在答案中)。
public class DecimalConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return value.ToString();
    }
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return decimal.Parse(value as string);
    }
}

我的绑定现在看起来像这样:

<TextBox Text="{Binding EditQty, Mode=TwoWay, Converter={StaticResource DecimalConverter}}" InputScope="Number" />

1
有时在处理具有替代可视树的弹出窗口/控件时会发生这种情况。某些属性不会级联。每当我遇到这种情况时,我使用一个来打印的类型:
<CommandBar>
   <AppBarButton Icon="Edit" AllowFocusOnInteraction="true">
      <Flyout>
         <StackPanel>
            <TextBlock Text="{Binding}" /> <!-- This will print typeof DataContext -->

            <TextBlock Text="Enter Qty:" />
            <TextBox Text="{Binding EditQty, Mode=TwoWay}" InputScope="Number" />
            <Button Content="Update" Command="{Binding EditCommand}" />
         </StackPanel>
      </Flyout>
<CommandBar>

如果那个TextBlock为空,那么你就知道DataContext没有传递到你的Flyout

如果您想要更新它,可以使用 DataContext=null;DataContext=xx - lindexi
我没有怀疑绑定有问题的两个原因:1)EditCommand没问题,2)我可以从VM设置EditQty并且值正确显示。我按照你建议的打印出Datacontext进行测试,它显示了我的VM,符合预期。 - Rkand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接