[英]WPF Cross User Control Data Binding
我有兩個用戶控件,一個帶有輸入字段(控件 A ),另一個帶有數據網格(控件 B )。 如何在WPF 的文本框中顯示網格視圖所選項目? 是否可以僅使用 WPF 或必須在程序代碼中執行或兩者都執行?
控制 A 與
<UserControl x:Class="PayrollSystem.Controls.EmployeeDetailControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock Text="First Name : " Grid.Column="0" Grid.Row="2" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<StackPanel Margin="2" Grid.Column="1" Grid.Row="2" Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox x:Name="txtFirstName" Text="{Binding Path=FirstName, Mode=TwoWay}" Width="200"/>
</StackPanel>
控制 B 與
<UserControl x:Class="PayrollSystem.Controls.EmployeeRecordControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataGrid x:Name="dg" AlternatingRowBackground="Gray" CanUserAddRows="False" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName, Mode=TwoWay}"/>
</DataGrid.Columns>
EmployeeRecordControl 似乎是多余的。 取而代之的是,直接使用 DataGrid,並將其ItemsSource
和SelectedItem
綁定到視圖模型類的兩個屬性,如下所示:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Employee> Employees { get; }
= new ObservableCollection<Employee>();
private Employee selectedEmployee;
public Employee SelectedEmployee
{
get => selectedEmployee;
set
{
selectedEmployee = value;
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(nameof(SelectedEmployee)));
}
}
}
然后像這樣創建並綁定到視圖模型:
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<DataGrid ItemsSource="{Binding Employees}"
SelectedItem="{Binding SelectedEmployee}"
CanUserAddRows="False"/>
<local:EmployeeDetailControl Grid.Column="1"
DataContext="{Binding SelectedEmployee}"/>
</Grid>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.