wpf - 通过 ViewModel 绑定(bind)到 DependencyProperty 无效

标签 wpf mvvm binding dependency-properties code-behind

我已经简化了我的问题(这意味着原理相似,但我不想将 int 转换为 string ...):

MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication1="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="500" Width="500">
    <Grid>

        <WpfApplication1:UserControl1 CurrentNumber="{Binding Path=TheSpecialNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

    </Grid>
</Window>

在主窗口中出现的是 UserControl1。用户控件有一个属性 Current Number。这个我想绑定(bind)属性TheSpecialNumber(ViewModel)。

MainWindow.xaml.cs:
namespace WpfApplication1
{
    public partial class MainWindow
    {
        private readonly ViewModel _viewModel;

        public MainWindow()
        {
            InitializeComponent();
            _viewModel = new ViewModel();
            DataContext = _viewModel;

            _viewModel.TheSpecialNumber = "8";
            _viewModel.UpdateTheSpecialNumberBinding();
        }
    }
}

ViewModel.cs:
namespace WpfApplication1
{
    class ViewModel : INotifyPropertyChanged
    {
        public string TheSpecialNumber { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public void UpdateTheSpecialNumberBinding()
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("TheSpecialNumber"));
            }
        }
    }
}

UserControl1.xaml:
<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             Height="200" Width="300" Background="Aqua">
    <Grid Name="container">
        <ComboBox SelectedIndex="{Binding Path=CurrentNumberIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            <ComboBoxItem Height="20">0</ComboBoxItem>
            <ComboBoxItem Height="20">1</ComboBoxItem>
            <ComboBoxItem Height="20">2</ComboBoxItem>
            <ComboBoxItem Height="20">3</ComboBoxItem>
            <ComboBoxItem Height="20">4</ComboBoxItem>
            <ComboBoxItem Height="20">5</ComboBoxItem>
            <ComboBoxItem Height="20">6</ComboBoxItem>
            <ComboBoxItem Height="20">7</ComboBoxItem>
            <ComboBoxItem Height="20">8</ComboBoxItem>
            <ComboBoxItem Height="20">9</ComboBoxItem>
        </ComboBox>
    </Grid>
</UserControl>

UserControl 是一个组合框。这有 10 个项目。我想始终显示与属性当前编号具有相同编号的项目。因此,绑定(bind)了Current Number Index。

UserControl1.xaml.cs:
using System;
using System.ComponentModel;
using System.Windows;

namespace WpfApplication1
{
    public partial class UserControl1 : INotifyPropertyChanged
    {
        public static readonly DependencyProperty CurrentNumberProperty = DependencyProperty.Register("CurrentNumber", typeof(string), typeof(UserControl1));

        public UserControl1()
        {
            InitializeComponent();
            container.DataContext = this;

            CurrentNumber = "5";
        }

        public string CurrentNumber
        {
            get { return (string)GetValue(CurrentNumberProperty); }
            set
            {
                SetValue(CurrentNumberProperty, value);
                OnPropertyChanged("CurrentNumberIndex");
            }
        }

        public int CurrentNumberIndex
        {
            get
            {
                return Convert.ToInt32(CurrentNumber);
            }
            set
            {
                CurrentNumber = Convert.ToString(value);
            }
        }

        #region Implementation of INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion Implementation of INotifyPropertyChanged
    }
}

现在我的问题。如果我在 MainWindow(通过 ViewModel)设置 8,为什么只显示 ComboBox 项目的内容为 0?即使我在 Current Number 的 setter 中设置断点,我也只会停止一次,即在 5 处,而不是在 8 处。

最佳答案

您可以通过手动设置 CurrentNumber=5 来“破坏” TheSpecialNumber 和 CurrentNumber 之间的绑定(bind)。删除此部分并重试。

编辑:
好的,如果这不起作用,请尝试以下操作:

  • 将新的 PropertyChangedCallback 添加到您的 PropertyMetaData:
    public static readonly DependencyProperty CurrentNumberProperty = DependencyProperty.Register("CurrentNumber", typeof(string), typeof(UserControl1), new PropertyMetadata( new PropertyChangedCallback(CurrentNumberPropertyChanged))); 
    
  • 在此方法中设置 CurrentNumber,例如:
    private static void CurrentNumberPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        UserControl1 uc1 = (UserControl1)dependencyObject;
        uc1.CurrentNumber = (string)dependencyPropertyChangedEventArgs.NewValue;
    }
    
  • 关于wpf - 通过 ViewModel 绑定(bind)到 DependencyProperty 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12595672/

    相关文章:

    wpf - 如何将WPF ScrollViewer的内容滚动到特定位置

    WPF - 启动时元素何时显示在屏幕上?

    wpf - 当 DataGrid 中进行数据绑定(bind)时,CommandParameter 未传递到 CanExecute(CanExecute 参数为 null)

    c# - 在C#中的ViewModel中公开模型中的枚举

    WPF ValueConverter 绑定(bind) - 出了点问题

    c# - WPF 延迟绑定(bind)无法正常工作

    c# - 传播 DependencyProperty 默认值

    .net - WPF ListView 非事件选择颜色和元素字体颜色

    Wpf 样式 : Binding to Child Property via ElementName

    wpf - BindingExpression 生成的值对目标无效