c# - XAML 数据绑定(bind)在属性更改时不更新 UI

标签 c# wpf xaml data-binding inotifypropertychanged

当整数字段更改时,我无法获取要更新的简单数据绑定(bind)标签。我已经实现了 INotifyPropertChanged,当我更改变量值时会触发此事件。 UI 不会更新,标签也不会更改。我过去没有做过太多数据绑定(bind),所以我可能遗漏了一些东西,但我还没有找到它。

这是我的 XAML:

         <Window x:Class="TestBinding.MainWindow" 
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:mc="http://schemas.openxmlformats.org/markup-
                compatibility/2006"
                xmlns:local="clr-namespace:TestBinding"
                mc:Ignorable="d"
                Title="MainWindow" Height="350" Width="525">
            <StackPanel>
                <Button Command="{Binding TestCommand, Mode=OneWay}" >
                    <Button.DataContext>
                        <local:TestVM/>
                    </Button.DataContext> Add 1</Button>
                <Label Content="{Binding Count,
                 Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
                    <Label.DataContext>
                        <local:TestVM/>
                    </Label.DataContext>
                </Label>
            </StackPanel>
        </Window>

这是我的 C# View 模型:

class TestVM : INotifyPropertyChanged
    {
        private int _count;
        private RelayCommand _testCommand;

        public TestVM ()
        {
            Count=0;

        }

        public int Count
        {
            get { return _count; }
            set { _count = value; OnPropertyChanged(); }
        }

        public void Test()
        {
            Count++;
        }

        public ICommand TestCommand
        {
            get
            {
                if (_testCommand == null)
                {
                    _testCommand = new RelayCommand(param => this.Test(), param => true);
                }

                return _testCommand;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
        {
            if (this.PropertyChanged != null)
            {
                Console.WriteLine(propertyName);
                var e = new PropertyChangedEventArgs(propertyName);
                this.PropertyChanged(this, e);
            }
        }
    }

这是我的 ICommand C#(如果您需要它来复制我拥有的内容):

public class RelayCommand : ICommand
    {
        #region Fields 
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;
        #endregion // Fields 

        #region Constructors 
        public RelayCommand(Action<object> execute) : this(execute, null) { }
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null) throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }
        #endregion // Constructors 

        #region ICommand Members [DebuggerStepThrough] 
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
        #endregion
        // ICommand Members 
    }

非常感谢任何帮助。

编辑: 我将我的 xaml 更新为 toadflakz 建议的内容并且有效。

<Window x:Class="TestBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestBinding"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:TestVM/>
    </Window.DataContext>
    <StackPanel>
    <Button Command="{Binding TestCommand, Mode=OneWay}" >Add 1</Button>
    <Label Content="{Binding Count, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Window>

最佳答案

您的问题在于将 DataContext 绑定(bind)到各个控件的方式。您的 ViewModel 不会自动成为单例(仅限单个实例的对象),因此每次指定它时,您实际上是在创建一个单独的实例。

如果您在窗口级别设置 DataContext,您的代码应该按预期工作。

关于c# - XAML 数据绑定(bind)在属性更改时不更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36647844/

相关文章:

wpf - 如何从 WPF 中的私有(private)内部类声明资源?

wpf - 绑定(bind)元素名称。它使用可视树还是逻辑树

c# - 代码隐藏中的 WPF UserControl 动画不适用于 ContentPresenter

c# - 如何为我的 Web 应用程序创建 MSI?

c# - ASP.NET 中的灵活 ACL

c# - 是否可以在有人连接之前在 WCF 服务中执行启动代码?

wpf - 如何在属性上触发 Storyboard

c# - HierachicalDataTemplate 和带有 ItemsControl 的 DataTemplate 之间的区别

c# - Windows Phone 8 - 在项目中的现有 txt 文件中读写

c# - 使用 ReSharper 在 C# 中的大括号后缩进