1

我一直在使用 MVVM 的 RelayCommand 成功地将操作绑定到 XAML,但是我的 ItemsControl 有一个小问题。

    <ItemsControl ItemsSource="{Binding Devices}" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid Width="100" Margin="4" >
                    <Button Command="{Binding Path=SelectDeviceCommand}" >
                        <Grid>
                            <Image Source="img_small.png"></Image>
                            <Image Source="{Binding Path=Logo}" />
                        </Grid>
                    </Button>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

在我的视图模型中:

    public RelayCommand SelectDeviceCommand { get; set; }
    private ObservableCollection<Device> Devices;

    Devices = CreateListOfDevices();

    private void InitializeCommands()
    {
        SelectDeviceCommand = new RelayCommand((s) => MessageBox.Show(s.ToString()));
    }

如何在我的视图模型中定义我的 SelectDeviceCommand 以接收绑定到该项目的对象?

我的 SelectDeviceCommand 甚至没有被调用......(但我猜是因为我需要将我的设备设为迷你视图模型并在其中实现 SelectDeviceCommand,对吗?)

4

3 回答 3

4

如果您在 MVVM Light 应用程序中使用 ViewModelLocator,您可以从 DataTemplate 中获取对 MainViewModel 的引用

<Button Command="{Binding Main.SelectDeviceCommand, Source={StaticResource Locator}}">

我发现这种方式比 ElementName 更干净,但当然它假设 Main 属性在定位器中可用,并且 MainviewModel 被实例化为单例。显然,这并不总是可能的。在这种情况下,我认为 ElementName 解决方法是可以接受的。

在 WPF 中,您还可以使用 Mode=FindAncestor 的 RelativeSource,但我发现它更加混乱;)

关于“如何在我的视图模型中定义我的 SelectDeviceCommand 以接收绑定到该项目的对象?”的问题,我不是 100% 确定我理解了这个问题,但是如果你想获取该项目(在在这种情况下是由 DataTemplate 表示的设备),您应该使用 CommandParameter:

<Button Command="{Binding Main.SelectDeviceCommand, Source={StaticResource Locator}}"
        CommandParameter="{Binding}"}">

干杯,劳伦特

于 2010-05-11T02:38:14.823 回答
0

是的,我打过这个。我已经看到有些人使用自定义的“CommandReference”类来解决它,他们将其作为资源添加到窗口中,但我无法让它工作。

最后,我使用元素绑定回到窗口(或页面)本身,因为 ViewModel 是窗口的 DataContext。首先,给你的窗口(或页面)一个名字:

<Window ...
    x:Name="me" />

然后直接绑定到窗口的datacontext,像这样:

<Button Command="{Binding DataContext.SelectDeviceCommand,ElementName=me}">

这对我有用。它很乱,但我认为它非常可读。

于 2010-05-11T01:50:59.403 回答
0

我有一个 usercontrol(x:Name="ControlClass") 它在模板内,它不适用于 xaml 我这样称呼它

<Button Content="New1" Command="{Binding DataContext.NewTabCommand,ElementName=ControlClass}"/>



namespace Doit_Project.Modules.Tasks.ViewModels
{
    [Export]
    public class WindoTabViewModel : Doit_ProjectViewModelBase
    {
        public WindoTabViewModel()
        {

        }

        private RelayCommand _newTabCommand;
        public RelayCommand NewTabCommand
        {
            get { return _newTabCommand ?? (_newTabCommand = new RelayCommand(OnNewTab)); }
        }

        public void OnNewTab()
        {

        }
    }
}
于 2010-05-14T03:13:44.127 回答