【发布时间】:2019-12-12 23:30:46
【问题描述】:
我正在使用 MVVM 设计模式编写简单的 WPF 应用程序。我的应用程序包含一个带有单个数据网格视图的用户控件。数据网格的每个单元格都是一个文本框列。
我想要的是在数据网格视图中设置焦点第一个单元格的文本框。
我尝试了this 解决方案,它适用于文本框。但它不适用于网格单元内的文本框。
Item.cs 类如下。
public class Item
{
public string ItemCode { get; set; }
public string ItemName { get; set; }
public double ItemPrice { get; set; }
public Item(string itemCode,string itemName, double itemPrice)
{
this.ItemCode = itemCode;
this.ItemName = itemName;
this.ItemPrice = itemPrice;
}
}
ItemsViewModel.cs 类如下
public class ItemsViewModel : INotifyPropertyChanged
{
private List<Item> _items;
public List<Item> ItemsCollection
{
get { return this._items; }
set
{
_items = value;
OnPropertyChanged(nameof(ItemsCollection));
}
}
public ItemsViewModel()
{
this.ItemsCollection = new List<Item>();
this.ItemsCollection.Add(new Item("", "", 0));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Item.xaml 用户控件如下。
<UserControl x:Class="WpfApp2.Items"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<StackPanel Orientation="Vertical">
<DataGrid x:Name="grdItems" ItemsSource="{Binding ItemsCollection}" AutoGenerateColumns="False" ColumnWidth="*">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Item Code">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox x:Name="txtItemCode" Text="{Binding ItemCode}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Item Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox x:Name="txtItemName" Text="{Binding ItemName}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Price">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox x:Name="txtItemSellingPrice" Text="{Binding ItemPrice}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
MainWindow.xaml 如下。
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<local:Items/>
</Grid>
【问题讨论】: