c# - 弹出式文本框双向绑定(bind)

标签 c# mvvm uwp

我正在尝试在弹出窗口中设置我的文本框文本绑定(bind),但从未调用我的 View 模型的绑定(bind)属性 setter 。我有这样的 View 设置:

<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>

我的 View 模型代码也很简单:

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

我什至尝试将 UpdateSourceTrigger=Explicit 与绑定(bind)一起使用,然后在按钮的单击事件中,设置代码隐藏以调用

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

在调试过程中,我可以看到 textBox.Text 值已正确更改,但 UpdateSource() 仍未调用 setter。如果重要的话,我使用的是 Windows 10 Build 14393(周年纪念版)。

有没有办法做到这一点?在这一点上,我将不得不放弃这个想法并将文本框放在对话框中,即使将它放在弹出窗口中会带来更好的用户体验。

最佳答案

根据 Microsoft ,自 WinRT 时代以来,UWP 就无法对十进制进行双向绑定(bind)! (原因是:不要问!)他们的解决方案是使用 float 。

如果您真的需要绑定(bind)到小数,您似乎可以使用 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);
    }
}

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

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

关于c# - 弹出式文本框双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48068188/

相关文章:

C# UWP 如何在 xaml 中显示 string[]?

c# - Visual Studio 无法识别版本 10.0.14393.0 中的 Windows 10 SDK

c# - 提交 C# MapReduce 作业 Windows Azure HDInsight - 响应状态代码不表示成功 : 500 (Server Error)

c# - 从 C# 执行 SSIS 包

c# - 我怎样才能弄清楚刚刚运行的代码是什么?

c# - 替换 DocumentDB 中的文档不保存更改

mvvm - MVVM中的模型职责

c# - 将 Entity Framework 导航属性映射到ViewModel对象

wpf - 本地化基于MVVM的WPF应用程序

c# - 拉动刷新 UWP - GridView ?