【发布时间】:2016-02-16 13:49:57
【问题描述】:
MVVM 新手,我正在尝试了解如何将命令绑定到数据模板中包含的控件。这是我的 XAML 目前的样子:
<UserControl>
<Grid>
<ListBox Grid.Row="1" x:Name="listBox1" ItemsSource="{Binding MyObservableCollection}" SelectionMode="Single">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBoxItem>
<ListBoxItem.ContextMenu>
<ContextMenu>
<MenuItem Header="Apply"/>
</ContextMenu>
</ListBoxItem.ContextMenu>
<Imagin.Controls:Thumbnail Source="{Binding ImageSource}"/>
</ListBoxItem>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" IsItemsHost="True"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="1,0" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
需要明确的是,我可以使用我的视图模型很好地将我的 observable 集合绑定到 ListBox。我有一个看起来像这样的视图模型类:
using System;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.Drawing;
using Imagin.Imaging;
using System.Collections.Generic;
namespace MyViewModelNameSpace
{
public class MyObject
{
private string name = "";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private ImageSource imageSource = null;
public ImageSource ImageSource
{
get
{
return imageSource;
}
set
{
imageSource = value;
}
}
public MyObject()
{
}
public MyObject(string Name, ImageSource ImageSource)
{
this.Name = Name;
this.ImageSource = ImageSource;
}
}
public class MyViewModel : ASimplerViewModel
{
public MyViewModel(MainWindowViewModel mainWindowViewModel)
{
if (mainWindowViewModel == null)
{
throw new ArgumentNullException("mainWindowViewModel");
}
this.MainWindowViewModel = mainWindowViewModel;
}
private MainWindowViewModel MainWindowViewModel
{
get;
set;
}
private ObservableCollection<MyObject> myObservableCollection = new ObservableCollection<MyObject>();
public ObservableCollection<MyObject> MyObservableCollection
{
get
{
return myObservableCollection;
}
set
{
myObservableCollection = value;
}
}
}
}
我试过这样绑定命令:
<ListBox MouseDown="SomeMouseDownEvent">
但我不知道在哪里定义事件?我也试过:
<ListBox MouseDown="{Binding SomeEventInMyViewModelClass}">
但我收到一条错误消息,提示您无法以这种方式绑定事件。
如何使用 MVVM 适当地定义命令并将它们绑定到数据模板中的对象?
【问题讨论】:
-
在代码隐藏中。 xaml.cs
-
不能从 MyViewModel 类中绑定?
-
我必须能够访问 MainWindowViewModel 类的成员,这些成员链接到 MyViewModel 类。我可以在数据模板中访问 MyViewModel 成员,但不能在 xaml.cs 中访问。
-
stackoverflow.com/questions/4897775/… 你在这里找到答案:)
标签: c# wpf mvvm data-binding datatemplate