Silverlight XAML:引用代码隐藏类

发布于 2024-08-13 18:40:11 字数 1154 浏览 2 评论 0原文

假设以下视图模型定义:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乞讨 2024-08-20 18:40:11

您需要一个 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文