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

时间:2014-12-14 08:27:35

标签: 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#代码中创建这些按钮的方式和位置。

1 个答案:

答案 0 :(得分:3)

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

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

相关问题