奇怪的WPF数据绑定行为

时间:2015-01-23 18:31:41

标签: c# wpf xaml mvvm

我试图让一些数据绑定在我的应用程序中工作,但我遇到了很多问题。这是一个例子:

这不起作用:(文本块中没有显示文本,但是触发了UpdateConsole功能,TextPercentage IS更新,如果我打破它< /强>)

SmallWindow.xaml:

<Button Content="Button" Click="Button_Click1"/>
<TextBlock HorizontalAlignment="Left"  Text="{Binding TextPercentage}">

SmallWindows.xaml.cs(删除了一些不相关的逻辑)

public partial class SmallWindow : Window
{
     public SmallWindow()
     {
      DataContext = new ViewModel();

      private void Button_Click1(object sender, RoutedEventArgs e)
      {
        ViewModel mv = new ViewModel();
        mv.UpdateConsole();
      }
  }
}

ViewModel.cs(删除了其他不相关的代码)

private string textPercentage;
    public string TextPercentage
    {
        get { return textPercentage; }
        set
        {
            textPercentage = value;
            RaisePropertyChanged("TextPercentage");
        }
    }
private void RaisePropertyChanged(string propertyName)
    {
        // take a copy to prevent thread issues
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

 public event PropertyChangedEventHandler PropertyChanged;

     public void UpdateConsole()
    {
        ++_count;
        TextPercentage= string.Format("{0}", _count);
    }

此操作:(文本显示在文本块中)

Smallwindow.xaml

<Button Content="Button" Command="{Binding ChangeSongCommand}"/>
<TextBlock HorizontalAlignment="Left"  Text="{Binding TextPercentage}"/>

SmallWindow.xaml.cs

public partial class SmallWindow : Window
{
     public SmallWindow()
     {
      DataContext = new ViewModel();
     }
}

ViewModel.cs(删除了其他不相关的代码)

private string textPercentage;
    public string TextPercentage
    {
        get { return textPercentage; }
        set
        {
            textPercentage = value;
            RaisePropertyChanged("TextPercentage");
        }
    }
private void RaisePropertyChanged(string propertyName)
    {
        // take a copy to prevent thread issues
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

 public ICommand ChangeSongCommand { get { return new RelayCommand(UpdateConsole); } }

 public event PropertyChangedEventHandler PropertyChanged;

    public void UpdateConsole(object obj)
    {
        ++_count;
        TextPercentage= string.Format("{0}", _count);
    }

所以,主要区别在于,第二个有效的,是由ICommand触发的。

整天都在与这场斗争,我不知道为什么会这样? 有点初学者,所以请简单回答:)

1 个答案:

答案 0 :(得分:2)

原因是你没有在正确的对象上调用方法:

// Create a separate view model object, which the current view is not bound to
ViewModel mv = new ViewModel();
mv.UpdateConsole();

这将创建一个新对象并在其上调用UpdateConsole,但WPF视图正在查看ViewModel属性引用的DataContext实例。

你想要的是:

// Get the view model object the view is presently bound to
ViewModel mv = (ViewModel)DataContext;
mv.UpdateConsole();