繁体   English   中英

WPF 跨用户控件数据绑定

[英]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,并将其ItemsSourceSelectedItem绑定到视图模型类的两个属性,如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM