【问题标题】:Create buttons programmatically with unique id以编程方式创建具有唯一 ID 的按钮
【发布时间】:2014-12-14 08:27:34
【问题描述】:

我创建了一些按钮,首先填充一个包含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# 代码中如何或在何处创建这些按钮。

【问题讨论】:

    标签: c# wpf xaml button dynamic


    【解决方案1】:

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

    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 程序集。

    【讨论】:

    • 感谢 Grx70 的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    相关资源
    最近更新 更多