爲什麼listbox中的按鈕無法運行綁定命令? 我將這個命令綁定到了簡單的按鈕(不是模板),它的工作完美。 Main.xaml爲什麼列表框模板中的綁定命令無法運行?
<Window x:Class="WpfApplication2.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:WpfApplication2"
mc:Ignorable="d"
Title="MainWindow" Height="800" Width="525">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="lbTemp">
<StackPanel>
<TextBlock Height="50" Text="{Binding}"/>
<Button Height="20" Content="click" Command="{Binding Path=TestCommand}" CommandParameter="hello"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox x:Name="listBox" Width="500" Height="300" ItemTemplate="{StaticResource lbTemp}" ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=DataContext.MyData}"/>
<Button Command="{Binding Path=TestCommand}" CommandParameter="hello" Width="200" Height="40"/>
</Grid>
ViewModel.cs
public class ViewModel : INotifyPropertyChanged
{
public ViewModel() { }
public ObservableCollection<string> MyData {
get
{
return _MyData;
}
set
{
if (!_MyData.SequenceEqual(value))
{
_MyData = value;
}
OnPropertyChanged();
}
}
private ObservableCollection<string> _MyData = new ObservableCollection<string>();
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string caller="")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(caller));
}
private ICommand _testCommand;
public ICommand TestCommand
{
get
{
return _testCommand;
}
set
{
if (_testCommand != value)
{
_testCommand = value;
OnPropertyChanged();
}
}
}
}
而且Command.cs
public class RelayCommand : ICommand
{
public RelayCommand(Action action, Func<object, bool> canExecutePredicate)
{
if (action == null || canExecutePredicate == null)
throw new ArgumentNullException("Can't be null");
this._action = action;
this._canExecutePredicate = canExecutePredicate;
}
public RelayCommand(Action action) : this(action, (obj) => true) { }
Action _action;
Func<object, bool> _canExecutePredicate;
public event EventHandler CanExecuteChanged;
protected virtual void OnCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
public bool CanExecute(object parameter)
{
return _canExecutePredicate(parameter);
}
public void Execute(object parameter)
{
_action?.Invoke();
}
}
你能說這個解決方案有效的XAML的例子嗎?
謝謝!完美地工作! – Alexey