Silverlight XAML:引用代码隐藏类
假设以下视图模型定义:
public class MyObject {
public string Name { get; set; }
}
public interface IMyViewModel {
ICommand MyCommand { get; }
IList<MyObject> MyList { get; }
}
和一个带有以下代码的 UserControl:
public class MyView : UserControl {
public IMyViewModel Model { get; }
}
如果我的 XAML 如下所示:
<UserControl>
<ListBox ItemsSource="{Binding MyList}">
<ListBox.ItemTemplate>
<TextBlock Text="{Binding Name}" />
<Button Content="Execute My Command" cmd:Click.Command="{Binding Path=MyCommand, ?????????}" cmd:Click.CommandParameter="{Binding}" />
</ListBox.ItemTemplate>
</ListBox>
如何将我的 Button
绑定到代码隐藏类的 ICommand
属性?
我正在使用 Prism 和 SL 3.0,我需要将列表框中的每个按钮绑定到视图模型上的相同命令。
在我的 UserControl
具有特定名称并且我能够使用 ElementName
绑定之前,但现在我的 UserControl
在同一个父级中多次使用view 所以我不能再使用该技术,并且我不知道如何在 XAML 中执行此操作。
如果这是我唯一的选择,我可以在代码隐藏中手动执行此操作,但如果可能的话,我宁愿在 XAML 中以声明方式执行此操作。
Assuming the following view model definition:
public class MyObject {
public string Name { get; set; }
}
public interface IMyViewModel {
ICommand MyCommand { get; }
IList<MyObject> MyList { get; }
}
And a UserControl with the following code behind:
public class MyView : UserControl {
public IMyViewModel Model { get; }
}
If my XAML looked like this:
<UserControl>
<ListBox ItemsSource="{Binding MyList}">
<ListBox.ItemTemplate>
<TextBlock Text="{Binding Name}" />
<Button Content="Execute My Command" cmd:Click.Command="{Binding Path=MyCommand, ?????????}" cmd:Click.CommandParameter="{Binding}" />
</ListBox.ItemTemplate>
</ListBox>
How can I bind my Button
to the ICommand
property of my code-behind class?
I'm using Prism and SL 3.0 and I need to bind each button in my list box to the same command on my view model.
Before my UserControl
had a specific name and I was able to use the ElementName
binding, but now my UserControl
is used multiple times in the same parent view so I can't use that technique anymore and I can't figure out how to do this in XAML.
If it is my only option I can do it manually in the code-behind, but I'd rather do it declaratively in the XAML, if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要一个 DataContextProxy 才能正常工作,因为您不再处于 UserControl 的上下文中。您已经摆脱了这种情况,如果没有像 DataContextProxy 这样的东西,就没有什么好方法可以返回到该上下文。我已经将它用于我的项目并且效果很好。
You need a DataContextProxy for this to work because you're no longer in the context of the UserControl. You've moved out of that and there is no good way to reach back into that context without something like the DataContextProxy. I've used it for my projects and it works great.