WPF MVVM设计问题
在我的视图中,我有一个带有事件“TreeView_MouseLeftButtonDown”的TreeView。如果它触发,则证明鼠标是否单击了 TreeViewItem。如果没有,它将取消选择最后一个 TreeViewItem。 我的问题是,我应该在代码隐藏中执行此操作还是在视图模型类中调用静态方法?你会如何解决这个问题?
方法:
private void treeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender != null)
{
var treeView = sender as TreeView;
if (treeView != null && treeView.SelectedItem != null)
TreeViewHelper.ReturnTreeViewItem(ref treeView, (XmlNode)treeView.SelectedItem).IsSelected = false;
}
}
XAML:
<TreeView ... KeyDown="TreeView_KeyDown"
MouseLeftButtonDown="TreeView_MouseLeftButtonDown"
SelectedItemChanged="TreeView_SelectedItemChanged" />
In my View I have a TreeView with a event "TreeView_MouseLeftButtonDown". If it fires it proofs if the mouse clicked on a TreeViewItem. If not it deselects the last TreeViewItem.
My question is, should i do this in the code-behind or call a static methode in the viewmodel-class? How would you solve this?
The Methode:
private void treeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender != null)
{
var treeView = sender as TreeView;
if (treeView != null && treeView.SelectedItem != null)
TreeViewHelper.ReturnTreeViewItem(ref treeView, (XmlNode)treeView.SelectedItem).IsSelected = false;
}
}
XAML:
<TreeView ... KeyDown="TreeView_KeyDown"
MouseLeftButtonDown="TreeView_MouseLeftButtonDown"
SelectedItemChanged="TreeView_SelectedItemChanged" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在尝试向 TreeView 中添加行为。
我实现这一点的方法是使用附加属性。我将创建一个名为
VerizesLeftClick
或类似的附加属性,并在其中实现逻辑。这样您就不需要在后面的代码中添加事件。有关示例,请参阅此处。
You are trying to add a behaviour to the TreeView.
The way I would implement this would be using Attached Properties. I would create an attached property called
VerifiesLeftClick
or similar and implement the logic in there. This way you do not need an event in the code behind.See here for samples.
我使用附加行为为您制作了解决方案,这里对此进行了很好的描述 WPF 中的附加行为简介Josh Smith
我的解决方案:
然后在视图中您应该添加以下内容:
我希望我的解决方案能够实现您想要实现的目标。
I made for you solution using attached behaviors which were pretty well described here Introduction to Attached Behaviors in WPF by Josh Smith
My solution:
and then in View you should add this:
I hope my solution do what you are trying to achieve.