gpt4 book ai didi

c# - 将按钮添加到数据模板并调用其点击事件

转载 作者:太空狗 更新时间:2023-10-30 00:08:22 25 4
gpt4 key购买 nike

我正在尝试构建一个 WPF 应用程序(使用 C#.net),我想在其中添加 ListBox 中的按钮。

这是我放在资源字典中的数据模板

<DataTemplate x:Key="MYTemplate">
<StackPanel Margin="4">
<DockPanel>
<TextBlock Text="ISBN No:" DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="AliceBlue" />
<TextBlock Text=" " />
<TextBlock Text="{Binding ISBN}" Foreground="LimeGreen" FontWeight="Bold" />
</DockPanel>
<DockPanel>
<TextBlock Text="Book Name:" DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="AliceBlue"/>
<TextBlock Text=" " />
<TextBlock Text="{Binding BookName}" Foreground="LimeGreen" FontWeight="Bold" />
</DockPanel >
<DockPanel >
<TextBlock Text="Publisher Name:" DockPanel.Dock="Left" Margin="5,0,10,0" Foreground="AliceBlue" />
<TextBlock Text=" " />
<TextBlock Text="{Binding PublisherName}" Foreground="LimeGreen" FontWeight="Bold" />
</DockPanel>
<DockPanel>
<Button Name="MyButton" Content="Click Me">

</Button>
</DockPanel>
</StackPanel>
</DataTemplate>

如何给上述模板中的按钮标签添加点击事件?另外,我应该在哪里放置单击按钮时将调用的方法。

最佳答案

尼勒什,

您应该使用将按钮绑定(bind)到命令。例如,如果您的数据项定义如下:

public class MyItem : ViewModelBase
{
public MyItem()
{
ClickMeCommand = new RelayCommand(ClickMe);
}

private void ClickMe()
{
Debug.WriteLine("I was clicked");
}

public string ISBN { get; set; }
public string BookName { get; set; }
public string PublisherName { get; set; }

public ICommand ClickMeCommand { get; set; }
}

然后这将调用 ClickMe 方法。

<DockPanel>
<Button Content="Click Me" Command="{Binding ClickMeCommand}" />
</DockPanel>

或者您可以将命令放在父 View 模型中:

public class MainViewModel : ViewModelBase
{
public IEnumerable<MyItem> Items { get; private set; }

/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Items = new List<MyItem>
{
new MyItem{ ISBN = "ISBN", BookName = "Book", PublisherName = "Publisher"}
};
ClickMeCommand = new RelayCommand<MyItem>(ClickMe);
}

private void ClickMe(MyItem item)
{
Debug.WriteLine(string.Format("This book was clicked: {0}", item.BookName));
}

public ICommand ClickMeCommand { get; set; }

并绑定(bind)到那个

<DockPanel>
<Button Content="Click Me" CommandParameter="{Binding}" Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}}, Path=DataContext.ClickMeCommand}" />
</DockPanel>

请注意,上面的代码使用的是 MVVM light,我假设您已经使用了

  <ListBox ItemTemplate="{StaticResource MyTemplate}" ItemsSource="{Binding Items}"/>

关于c# - 将按钮添加到数据模板并调用其点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9238787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com