c# - WPF 绑定(bind)到文本框不更新

标签 c# wpf textbox binding dependency-properties

我正在编写一个 WPF 应用程序,我有一个文本框供用户输入视频播放的每秒帧数值。这个文本框的值被绑定(bind)到代码背后的依赖属性(试图像一个好的设计师一样遵循 MVVM)。我的问题是当外部更改 FPS 值时,文本框不会自动更新。例如,用户可以使用 slider 控制值。 slider 正确更改了依赖属性值,但文本框文本永远不会更新,当然,除非我使用 GetBindingExpression(..).UpdateTarget() 手动执行它,这是我在等待更好的解决方案之前实现的。有谁知道这是预期的功能还是我设置有误?

谢谢, 最大

XAML 中的文本框标记:

<TextBox Text="{Binding FPS}" Name="tbFPS" FlowDirection="RightToLeft"/>

依赖属性的代码隐藏:

    #region public dependency property int FPS

    public static readonly DependencyProperty FPSProperty =
        DependencyProperty.Register("FPSProperty", typeof(int), typeof(GlobalSettings),
        new PropertyMetadata(MainWindow.appState.gSettings.fps,FPSChanged,FPSCoerce),
        FPSValidate);

    public int FPS
    {
        get { return (int)GetValue(FPSProperty); }
        set { SetValue(FPSProperty, value); }
    }

    private static bool FPSValidate(object value)
    {
        return true;
    }

    private static object FPSCoerce(DependencyObject obj, object o)
    {
        return o;
    }

    private static void FPSChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        //why do i need to update the binding manually? isnt that the point of a binding?
        //
        (obj as GlobalSettings).tbFPS.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
    }

    #endregion

最佳答案

不确定这是否是问题所在,但您应该传递“FPS”作为属性名称,而不是“FPSProperty”,如下所示:

public static readonly DependencyProperty FPSProperty =
    DependencyProperty.Register("FPS", typeof(int), typeof(GlobalSettings),
    new PropertyMetadata(MainWindow.appState.gSettings.fps,FPSChanged,FPSCoerce),
    FPSValidate);

关于c# - WPF 绑定(bind)到文本框不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6471605/

相关文章:

WPF:在同一列中带有复选框和文本框的 ListView

c# - 使用 protobuf.net 反序列化缺失类型

c# - Windows Phone 8.1 XAML : Put Enum Value into XAML Attribute

WPF:将所有选项列表和选定选项列表绑定(bind)到带有选择复选框的列表框

c# - ViewModel 应该如何引用它的 Models 属性?

wpf - 验证按钮单击事件 wpf c#

c# - 比较对象

c# - 小巧玲珑/SQL 服务器 : passing TVP to stored procedure with needed fields only

c# - 我应该如何连接字符串?

c# - 在自动回发功能后将焦点设置回正确的文本框(Page.SetFocus 不能解决问题)