我在.xaml文件中具有以下代码段:
<TreeView MouseDoubleClick="TreeView_MouseDoubleClick" ItemsSource="{Binding MyList}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="FontWeight" Value="Normal" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
如您所见,当您在TreeView中的某个项目上“ MouseDoubleClick”时,它将执行后面代码中的代码...即...
private void TreeView_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try
{
MessageBox.Show(((TreeViewWithViewModelDemo.LoadOnDemand.HtmlFileViewModel)(((System.Windows.Controls.TreeView)(sender)).SelectedValue)).HtmlFileName);
}
catch
{
}
}
我正在尝试遵循Model-View-ViewModel设计模式,并希望将此MouseDoubleClick事件的实现从View移到ViewModel中。
我知道,如果我使用的是命令,我会使用{Binding Command =“ Select”}(或类似的实现ICommand接口的东西),但由于它不是命令按钮,因此我似乎找不到该特定问题的语法。
有人可以帮我吗?
谢谢
最佳答案
这是使用Blend的交互触发器的解决方案。
<Page.DataContext>
<Samples:TreeViewDblClickViewModel/>
</Page.DataContext>
<Grid>
<TreeView ItemsSource="{Binding Items}">
<TreeView.ItemTemplate>
<DataTemplate>
<ContentControl>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding DoubleClickCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TextBlock Text="{Binding Name}" Background="AliceBlue" Margin="2"/>
</ContentControl>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
查看模型
public class TreeViewDblClickViewModel
{
public TreeViewDblClickViewModel()
{
Items = new List<TreeViewDblClickItem>
{
new TreeViewDblClickItem{ Name = "One"},
new TreeViewDblClickItem{ Name = "Two"},
new TreeViewDblClickItem{ Name = "Thee"},
new TreeViewDblClickItem{ Name = "Four"},
};
}
public IList<TreeViewDblClickItem> Items { get; private set; }
}
public class TreeViewDblClickItem
{
public TreeViewDblClickItem()
{
DoubleClickCommand = new ActionCommand(DoubleClick);
}
public string Name { get; set; }
private void DoubleClick()
{
Debug.WriteLine("Double click");
}
public ICommand DoubleClickCommand { get; private set; }
}
关于c# - 通过M-V-MV设计模式绑定(bind)MouseDoubleClick时出现问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9811538/