【问题标题】:WPF ItemsPanel with Caliburn.Micro MVVM带有 Caliburn.Micro MVVM 的 WPF ItemsPanel
【发布时间】:2017-10-02 05:55:11
【问题描述】:

我正在开发一个 WPF 应用程序并将Caliburn.Micro 用于 MVVM。我需要在运行时动态地将按钮添加到视图中。 我做了一些研究,我知道我可以使用 ItemControl 来实现这一点。

   <Window
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
      <Grid>  
      <ItemsControl>
      <Button x:Name="ExecuteMethod1" Content="Execute1" />
      <Button x:Name="ExecuteMethod2" Content="Execute2" />
      <Button x:Name="ExecuteMethod3" Content="Execute3" />
      </ItemsControl>
      </Grid>
    </Window>

Caliburn.Micro's 约定允许调用与 Button 的 x:Name 属性匹配的方法。上面代码中名为 ExecuteMethod1 的按钮将调用 ViewModel 中的方法 ExecuteMethod1()。

问题:

当我动态添加按钮时,如何设置按钮的 X:Name 属性? 我尝试使用Binding 设置它,但WPF 不允许绑定X:Name 属性。 有其他选择吗?谁能帮我提个建议?

【问题讨论】:

  • 您应该将 ItemsControl 的 ItemsSource 属性绑定到视图模型项的 ObservableCollection。视图模型项类将有两个属性,一个用于 Button 的 Content,一个用于其 Command。在 ItemsControl 的 ItemTemplate 中,您将声明一个 Button,并将其 Content 和 Command 属性绑定到视图模型项的属性。从这里开始阅读:Data Templating Overview.
  • @Clemens 如何在 CM 中绑定命令?能否提供代码示例?
  • 我试过了,效果很好:&lt;Button cal:Message.Attach="{Binding TestEvent}" Content="Test" /&gt;
  • @Rahul 嗨,你能分享一下你是如何做到这一点的吗?

标签: c# wpf mvvm caliburn.micro itemscontrol


【解决方案1】:

我不确定这是否是一项新功能。从 Caliburn Micro 文档中得到它的工作。 添加 Windows 交互程序集。您可以将按钮的名称或内容传递给您的操作,这足以识别单击了哪个按钮并执行正确的操作。 CaliburnMicro Actions

<UserControl x:Class="Caliburn.Micro.HelloParameters.ShellView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
             xmlns:cal="http://www.caliburnproject.org">
    <StackPanel>
        <TextBox x:Name="Name" />
        <Button Content="Click Me">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <cal:ActionMessage MethodName="SayHello">
                        <cal:Parameter Value="{Binding ElementName=Name, Path=Text}" />
                    </cal:ActionMessage>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
    </StackPanel>
</UserControl> 

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2013-10-02
    • 2019-09-09
    • 2012-12-27
    • 2011-09-25
    • 2012-06-04
    相关资源
    最近更新 更多