【发布时间】:2018-04-18 08:06:47
【问题描述】:
我正在开发一个小型 WPF 应用程序。单击按钮时,我想将按钮的内容从“播放”更改为“停止”。我的问题是 UI 没有改变,尽管我在调试时进入了命令。我究竟做错了什么?感谢您的帮助。
代码如下:
Xaml:
<Window x:Class="Cron.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:Cron"
mc:Ignorable="d"
Title="Cron" Height="450" Width="650" MinWidth="600">
<StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button Content="{Binding PlayButtonText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Command="{Binding StartStopCommand}"
VerticalAlignment="Top" Width="75"/>
</StackPanel>
</StackPanel>
C#: 这是视图模型。我想在这里设置按钮内容。
using System.Windows.Input;
namespace Cron
{
public class MasterWindowViewModel : BaseViewModel
{
public bool IsPlaying { get; set; } = false;
private string _playButtonText = "Play";
public string PlayButtonText
{
get => _playButtonText;
set => _playButtonText = value;
}
public ICommand StartStopCommand { get; set; }
public MasterWindowViewModel()
{
StartStopCommand = new RelayCommand(() => StartStop());
}
private void StartStop()
{
IsPlaying = !IsPlaying;
_playButtonText = IsPlaying ? "Stop" : "Play";
}
}
}
这是 RelayCommand。
using System;
using System.Windows.Input;
namespace Cron
{
/// <summary>
/// A basic command that runs an action.
/// </summary>
public class RelayCommand : ICommand
{
private Action _action;
public event EventHandler CanExecuteChanged = (sender, e) => { };
public bool CanExecute(object parameter) => true;
public RelayCommand(Action action)
{
_action = action;
}
public void Execute(object parameter)
{
_action();
}
}
}
这是底层的 BaseViewModel。
using System.ComponentModel;
namespace Cron
{
/// <summary>
/// Bas ViewModel wit PropertyChangedEvents.
/// </summary>
public class BaseViewModel : INotifyPropertyChanged
{
/// <summary>
/// The PropertyChangedEvent.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };
/// <summary>
/// Call this to fire a <see cref="PropertyChanged"/> event
/// </summary>
/// <param name="name"></param>
public void OnPropertyChanged(string name)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
数据上下文:
namespace Cron
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MasterWindowViewModel();
}
}
}
【问题讨论】:
-
你确定设置了数据上下文吗?输出窗口中是否有任何绑定失败?
-
我在上面的代码中设置了上下文。没有例外。
标签: c# .net wpf mvvm data-binding