在WPF中,可以通过使用多个Binding对象来实现多数据源绑定。这样可以避免生成多余的标记。

以下是一个示例,演示如何使用多个Binding对象来绑定多个数据源:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Text="{Binding Path=Name}" />
        <TextBox Text="{Binding Path=Age}" />
    </Grid>
</Window>

在上面的示例中,我们使用了两个Binding对象,一个用于将Name属性绑定到第一个TextBox的Text属性,另一个用于将Age属性绑定到第二个TextBox的Text属性。

我们还需要为每个Binding对象指定数据源。可以使用以下代码将数据源分配给Binding对象:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Person person = new Person();
        person.Name = "John";
        person.Age = 30;

        Binding binding1 = new Binding("Name");
        binding1.Source = person;
        textBox1.SetBinding(TextBox.TextProperty, binding1);

        Binding binding2 = new Binding("Age");
        binding2.Source = person;
        textBox2.SetBinding(TextBox.TextProperty, binding2);
    }
}

在上面的代码中,我们创建了一个Person对象,并将其分配给两个Binding对象。然后,我们将每个Binding对象分配给相应的TextBox控件的Text属性。

使用多个Binding对象可以简化XAML代码,并避免生成多余的标记。

wpf 不生成多余标记的 多数据源绑定

原文地址: https://www.cveoy.top/t/topic/bVTi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录