简体   繁体   English

带Caliburn.Micro MVVM的WPF ItemsPanel

[英]WPF ItemsPanel with Caliburn.Micro MVVM

I'm developing a WPF application and using Caliburn.Micro for MVVM. 我正在开发WPF应用程序,并将Caliburn.Micro用于MVVM。 I'need to dynamically add buttons into view during the runtime. 我需要在运行时动态地将按钮添加到视图中。 I have done some research and I got to know that I can achieve this using an ItemControl. 我已经做过一些研究,并且我知道我可以使用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 convention allows to call a method which matches to Button's x:Name property. Caliburn.Micro's约定允许调用与Button的x:Name属性匹配的方法。 In above code button named ExecuteMethod1 will call a method ExecuteMethod1() in ViewModel. 在上面的代码中,名为ExecuteMethod1的按钮将在ViewModel中调用方法ExecuteMethod1()。

Problem: 问题:

As I'm adding buttons dynamically how can I set the X:Name property for buttons? 在动态添加按钮时,如何设置按钮的X:Name属性? I tried to set it using Binding , but WPF doesn't allow to bind X:Name property. 我尝试使用Binding设置它,但是WPF不允许绑定X:Name属性。 Is there any alternatives? 还有其他选择吗? Could anyone can help me with a suggestion? 有人可以帮我一个建议吗?

I am not sure if this a new feature. 我不确定这是否是一项新功能。 Got it working from the Caliburn Micro Documentation. 从Caliburn Micro文档中获取了它的信息。 Add Windows Interactivity Assembly. 添加Windows交互程序集。 You can pass to your action the Name or the Content of the Button that shall be enough to identify which button was clicked and perform the right action. 您可以将按钮的名称或内容传递给您的操作,该操作应足以识别单击了哪个按钮并执行正确的操作。 CaliburnMicro Actions CaliburnMicro动作

<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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM