如何在 wpf 中将对象从一个窗口绑定到另一个窗口中的另一个控件?(C#)



我想将一个窗口中已经存在的对象绑定到另一个窗口中的文本框。我有这个对象(汽车)已经绑定到这个窗口-

public partial class Car_UI : Window
{
    BE.Car car = new BE.Car();//this is the object
public Car_UI()
    {
        InitializeComponent();
        this.DataContext = car;
    }
}

汽车领域之一是我想绑定到新风的结构 - 我试过这个,但它不起作用

 private void slc_ch_cartype(object sender, SelectionChangedEventArgs e)
    {
        ComboBoxItem lbi = ((sender as ComboBox).SelectedItem as ComboBoxItem);
        if ("other" == lbi.Content.ToString())
        {
            new carType_UI(){ DataContext =car.typecar/*this is the field in car I'm tring to bind*/}.Show();
        }
    }

这是车型

 public struct CarType
{
    public string Manufacturer;
    public  string Model;
    public  int Volume;
    public override string ToString()
    {
        string s = String.Format(
          @"Manufacturer: {0} Model: {1} Volume: {2}"
           , Manufacturer, Model, Volume);
        return s;
    }
}

这是 XAML 中的绑定-

<TextBox x:Name="txtbx_manf" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" >
        <TextBox.Text>
            <Binding Path="Manufacturer" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <local:StringRangeValidationRule MinimumLength="1" MaximumLength="50" ErrorMessage="Manufacturer is required to be at least 1 charecthers." />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

由于某种原因这不起作用,有人知道为什么吗?

谢谢,你的答案。字段不能绑定,只能绑定属性。

CarType结构中的属性实际上是一个字段,而不是属性,因此 WPF 绑定不会绑定到它。

您需要:

  • 确保文本框的数据上下文是CarType对象
  • 并且您使用正确的属性,而不是字段 - 最好还实现 INotifyPropertyChanged

从您的代码中,我可以看到制造商是在结构CarType中定义的。它不起作用的原因是

  • 结构体是一种值类型,绑定将获得它的副本,因此永远不会更新原始对象。

我建议你把车型改成

最新更新