我是MVVM模式的新手。我在更新文本块时遇到问题。我有一个文本块和菜单按钮。
//View.xaml for textblock
<Grid DataContext="{Binding Source={StaticResource MenuHandler}}" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Row="2" Grid.ColumnSpan="3" Margin="5,0,5,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=StatusText, UpdateSourceTrigger=PropertyChanged}" Name="StatusText" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Stretch" Width="100" IsEnabled="True" Height="23"/>
</Grid>
//View.xaml for Menu
<Menu DataContext="{Binding Source={StaticResource MenuHandler}}" Height="25" HorizontalAlignment="Stretch" Name="menu1" VerticalAlignment="Top" Visibility="Visible" Background="AliceBlue">
<MenuItem Header="_New" Command="{Binding NewFileCommand}" Name="NewFile" >
<MenuItem.Icon>
<Image Source="/WhitelistBlacklistEditor;component/Images/NewFile.png" Width="25"/>
</MenuItem.Icon>
</MenuItem>
</Menu >
在视图模型中,我正在使用MenuHandler类
// MenuHandler.cs
public string StatusText
{
get { return _StatusText; }
set
{
_StatusText = value;
RaisePropertyChangedEvent(StatusText);
}
}
public ICommand NewFileCommand
{
get { return new DelegateCommand(NewFile_Click); }
}
public void NewFile_Click()
{
StatusText = "checking";
}
如果我在NewFile_Click()方法之外更新StatusText,则值在文本块中更新,但如果我在NewFile_Click()中通过ICommand执行相同操作,则它不会更新。 我也通过INotifyPropertyChanged继承了MenuHandler类,并通过在xaml中添加twoway模式进行检查。
答案 0 :(得分:0)
public class DelegateCommand : ICommand
{
private readonly Predicate _canExecute; private readonly Action _execute;
public event Event Handler CanExecuteChanged;
public Delegate Command(Action<object> execute)
: this(execute, null)
{
}
public Delegate Command(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public override bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public override void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if( CanExecuteChanged != null )
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
private DelegateCommand _NewFileCommand;
public ICommand NewFileCommand
{
get
{
if (adcom == null)
adcom = new DelegateCommand(CommandExecuter, CommandExecute);
return adcom;
}
}
private bool CommandExecuter(object obj)
{
return true;
}
private void CommandExecute(object obj)
{
Statuscheck="";
}