【发布时间】:2012-09-03 20:14:24
【问题描述】:
我的问题与这个问题中描述的类似:
WPF MVVM Button Control Binding in DataTemplate
这是我的 XAML:
<Window x:Class="MissileSharp.Launcher.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MissileSharp Launcher" Height="350" Width="525">
<Grid>
<!-- when I put the button here (outside the list), the binding works -->
<!--<Button Content="test" Command="{Binding Path=FireCommand}" />-->
<ListBox ItemsSource="{Binding CommandSets}">
<ListBox.ItemTemplate>
<DataTemplate>
<!-- I need the button here (inside the list), and here the binding does NOT work -->
<Button Content="{Binding}" Command="{Binding Path=FireCommand}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
它只是一个 ListBox,绑定到一个名为 CommandSets 的 ObservableCollection<string>(在 ViewModel 中)。
此绑定有效(它为集合中的每个项目显示一个按钮)。
现在我想将按钮绑定到命令 (FireCommand),该命令也在 ViewModel 中。
这是 ViewModel 的相关部分:
public class MainWindowViewModel : INotifyPropertyChanged
{
public ICommand FireCommand { get; set; }
public ObservableCollection<string> CommandSets { get; set; }
public MainWindowViewModel()
{
this.FireCommand = new RelayCommand(new Action<object>(this.FireMissile));
}
private void FireMissile(Object obj)
{
System.Windows.MessageBox.Show("fire");
}
}
此按钮的绑定不起作用。
根据我从上面链接的question 中了解到的情况,绑定不起作用,因为:
(如果我错了,请纠正我)
- 按钮位于
ListBox内,因此它只“知道”ListBox的绑定(在本例中为ObservableCollection),而不是主窗口的绑定 - 我正在尝试绑定到主窗口的主 ViewModel 中的命令(按钮不“知道”)
命令本身绝对正确,因为当我将按钮放在ListBox 之外(请参阅上面的XAML 示例),绑定有效并且命令被执行。
显然,我“只是”需要告诉按钮绑定到表单的主 ViewModel。
但我无法找出正确的 XAML 语法。
我尝试了几种在谷歌搜索后发现的方法,但没有一个对我有用:
<Button Content="{Binding}" Command="{Binding RelativeSource={RelativeSource Window}, Path=DataContext.FireCommand}" />
<Button Content="{Binding}" Command="{Binding Path=FireCommand, Source={StaticResource MainWindow}}" />
<Button Content="{Binding}" Command="{Binding Path=FireCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
有人可以吗:
- 给我正确的 XAML 以将
ListBox中的按钮绑定到表单的MainViewModel中的命令? - 指向一个链接,其中以 WPF/MVVM 初学者可以理解的方式解释了这种高级绑定内容?
我觉得我只是在复制和粘贴神秘的 XAML 咒语,并且到目前为止,我没有任何线索(也找不到任何好的文档)我将如何自己弄清楚在哪些情况下我需要RelativeSource或StaticResource或其他任何东西而不是“正常”绑定。
【问题讨论】:
标签: c# wpf xaml data-binding mvvm