之前我这样做了50次。我真的不知道为什么这次不工作。我有一个WPF应用程序,我唯一的依赖是MahApps.Metro。我在我的按钮上使用它的MetroWindow和Dynamic Style。
这是最新的xaml:
<ItemsControl Grid.Column="0" Grid.Row="1" ItemsSource="{Binding ServerList}" Margin="5">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="LightGray">
<StackPanel Orientation="Horizontal">
<Button Style="{DynamicResource MetroCircleButtonStyle}" Content="{StaticResource appbar_monitor}" Command="{Binding VM.ServerSelectedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Controls:MetroWindow}}" CommandParameter="{Binding .}"></Button>
<Label Content="{Binding .}" HorizontalAlignment="Center" VerticalAlignment="Center"></Label>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这是我的ViewModel中的ServerSelectedCommand:
private ViewModelCommand _ServerSelectedCommand;
public ViewModelCommand ServerSelectedCommand
{
get
{
if (_ServerSelectedCommand == null)
{
_ServerSelectedCommand = new ViewModelCommand(
p => { SelectServer(p); },
p => true
);
}
return _ServerSelectedCommand;
}
set { _ServerSelectedCommand = value; }
}
private void SelectServer(object parameter)
{
}
ViewModelCommand类与RelayCommand类似。这是:
public class ViewModelCommand : Observable, ICommand
{
public bool CanExecuteValue
{
get { return CanExecute(null); }
}
public ViewModelCommand(
Action<object> executeAction,
Predicate<object> canExecute)
{
if (executeAction == null)
throw new ArgumentNullException("executeAction");
_executeAction = executeAction;
_canExecute = canExecute;
}
private readonly Predicate<object> _canExecute;
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged;
public void OnCanExecuteChanged()
{
OnPropertyChanged(() => CanExecuteValue);
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
private readonly Action<object> _executeAction;
public void Execute(object parameter)
{
_executeAction(parameter);
}
}
很抱歉代码很多。但我需要添加它们才能找到我看不到的问题。所以让我们回到第一个xaml,这是我尝试过的最新版本。以下是我为有问题的Button行尝试的代码。
Command="{Binding ServerSelectedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}}"
Command="{Binding ServerSelectedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ViewModel}}}"
这也没有提供任何东西!
Command="{Binding RelativeSource={RelativeSource AncestorType=Controls:MetroWindow}}"
谢谢!
答案 0 :(得分:5)
此绑定看起来像是在ItemsControl上查找ServerSelectedCommand:
Command="{Binding ServerSelectedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}}"
试试这个:
Command="{Binding DataContext.ServerSelectedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}}"
当然假设ItemsControl的DataContext是您的ViewModel。