如何在按钮点击处理程序中更好地获取类数据
本文关键字:更好 获取 数据 程序 处理 按钮 | 更新日期: 2023-09-27 17:49:33
我的问题是,是否可以以更优雅、更高效的方式重做工作解决方案。我不想在MVVM模式中重新制作整个东西,我更想的是将信息从点击处理程序传递到点击处理程序的更好方法,而不是将其内容的按钮剥离。
目的是有两个独立的员工列表——左边的列表是一个完整的员工列表,右边的列表是分配给某项任务的员工列表。
主页.XAML
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<GridView Grid.Column="0" x:Name="LeftGridView" ItemsSource="{Binding}">
<GridView.ItemTemplate>
<DataTemplate>
<Button Width="200" Height="200" Click="LeftListButtonClick" Background="Aqua">
<Button.Content>
<StackPanel Orientation="Vertical">
<Image Source="{Binding Photo}" Width="60" Height="60"/>
<TextBlock Width="100" Height="20" Text="{Binding FirstName}"/>
<TextBlock Width="100" Height="20" Text="{Binding Lastname}"/>
</StackPanel>
</Button.Content>
</Button>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<GridView Grid.Column="1" x:Name="RightGridView" ItemsSource="{Binding}">
<GridView.ItemTemplate>
<DataTemplate>
<Button Width="200" Height="200" Click="RightListButtonClick" Background="Aqua">
<Button.Content>
<StackPanel Orientation="Vertical">
<Image Source="{Binding Photo}" Width="60" Height="60"/>
<TextBlock Width="100" Height="20" Text="{Binding FirstName}"/>
<TextBlock Width="100" Height="20" Text="{Binding Lastname}"/>
</StackPanel>
</Button.Content>
</Button>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
类
class Person
{
public String FirstName { get; set; }
public String Lastname { get; set; }
public Image Photo { get; set; }
}
class PersonList : ObservableCollection<Person>
{
private ObservableCollection<Person> _leftList = new ObservableCollection<Person>();
public ObservableCollection<Person> LeftList
{
get { return _leftList; }
set { _leftList = value; }
}
private ObservableCollection<Person> _rightList = new ObservableCollection<Person>();
public ObservableCollection<Person> RightList
{
get { return _rightList; }
set { _rightList = value; }
}
}
最后是主页.XAML.CS
public sealed partial class MainPage : Page
{
PersonList newList = new PersonList();
public MainPage()
{
this.InitializeComponent();
Person p1 = new Person();
p1.FirstName = "John";
p1.Lastname = "Doe";
newList.LeftList.Add(p1);
Person p2 = new Person();
p2.FirstName = "Jane";
p2.Lastname = "Doe";
newList.LeftList.Add(p2);
LeftGridView.ItemsSource = newList.LeftList;
}
private void LeftListButtonClick(object sender, RoutedEventArgs e)
{
Button var = sender as Button;
StackPanel var2 = var.Content as StackPanel;
var var3 = var2.Children.ToArray();
Person p1 = new Person();
TextBlock tb1 = var3[1] as TextBlock;
p1.FirstName = tb1.Text;
TextBlock tb2 = var3[2] as TextBlock;
p1.Lastname = tb2.Text;
newList.RightList.Add(p1);
RightGridView.ItemsSource = newList.RightList;
}
private void RightListButtonClick(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
}
ICommand _addToRightCommand = new DelegateCommand<Person>(person => this.RightList.Add(person))
由于各种原因,这不会编译,但它应该让您知道该怎么做。