我创建了一些按钮,方法是首先填充一个包含 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/