c# - 使用唯一 ID 以编程方式创建按钮

标签 c# wpf xaml button dynamic

我创建了一些按钮,方法是首先填充一个包含 get/set 方法的类,然后在 XAML 中使用该信息。

C#

List<MediaDetail> movies = new List<MediaDetail>();
...
...
MovieListView.ItemsSource = movies;  

XAML

<Window.Resources>
    <DataTemplate x:Key="ItemTemplate">
        <WrapPanel Orientation="Vertical"  Width="Auto">
            <Button Width="200" Height="300" Click="SelectMovie_Click" Name ="NEED THIS TO BE DYNAMIC">
                <Button.Template>
                    <ControlTemplate>
                        <Image Source="{Binding image}"/>
                    </ControlTemplate>
                </Button.Template>
            </Button>
            <TextBlock Text="{Binding title}" HorizontalAlignment="Center"/>
        </WrapPanel>
    </DataTemplate>        
</Window.Resources>


<ListView Name="MovieListView" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Path = movies}" Margin="0,0,0,0" SelectionChanged="MovieListView_SelectionChanged" Grid.Row="1">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="5" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
    </ListView>

但问题是,我需要每个按钮都有一个唯一的 ID。我在别处读到这不能在 XAML 中完成,但我不确定在我的 C# 代码中如何或在何处创建这些按钮。

最佳答案

我认为这里最灵活的解决方案是定义一个行为:

public class UniqueNameBehavior : Behavior<FrameworkElement>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        //assign unique name to the associated element, for example:
        AssociatedObject.Name = Guid.NewGuid().ToString().Replace("-", null);
    }
}

在 XAML 中,将此行为附加到任何元素:

<Button>
    <i:Interaction.Behaviors>
        <local:UniqueNameBehavior/>
    </i:Interaction.Behaviors>
</Button>

其中 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 来自 System.Windows.Interactivity 程序集。

关于c# - 使用唯一 ID 以编程方式创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467594/

相关文章:

c# - WPF自定义控件库图片资源

WPF 绑定(bind)到元素属性的 XPath 可访问值

c# - 如何在 Web API MultiPartContent 消息上设置 "type"参数?

c# - 加载包含括号中的 JSON 的 JSON 文件

c# - 如何访问控件模板中的元素?

wpf - 在 WPF TabControl 上 - 我可以在选项卡标题旁边添加内容吗?

c# - 指定的对象或值不存在

c# - 为多个参数创建唯一键(缓存键)

c# - 在带有 Winforms 的 Visual Studio 2010 中将字符串与控件相关联的编程高效方法

c# - 如何从 xaml 中引用 .resx 文件中的图标?