WPF中的双向绑定 [英] TwoWay binding in WPF
问题描述
嗨
我在使用WPF中的twoway绑定时遇到问题。我有
Hi
I have a problem with getting twoway binding to work in WPF. I have
public List<AirlineMaintenanceMVVM> Maintenances { get; set; }
其中AirlineMaintenanceMVVM是:
where AirlineMaintenanceMVVM is:
public class AirlineMaintenanceMVVM
{
private MaintenanceCenterMVVM _selectedtype;
public AirlinerMaintenanceType Type { get; set; }
public MaintenanceCenterMVVM SelectedType
{
get
{
return this._selectedtype;
}
set
{
this._selectedtype = value;
this.NotifyPropertyChanged("SelectedType");
}
}
public ObservableCollection<MaintenanceCenterMVVM> Centers { get; set; }
public AirlineMaintenanceMVVM(AirlinerMaintenanceType type, MaintenanceCenterMVVM selected, List<MaintenanceCenterMVVM> centers)
{
this.Type = type;
this.Centers = new ObservableCollection<MaintenanceCenterMVVM>();
centers.ForEach(c => this.Centers.Add(c));
this.SelectedType = selected;
}
#region Public Events
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region Methods
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
在xaml中我创建了一个带有ComboBox的ListBox,其中组合框绑定元素和MVVM文件中的选定值。但是,当我创建MVVM对象时设置所选值时,在显示组合框时未设置该值:
In the xaml I have created a ListBox with a ComboBox inside, where the combo box binds to the elements and selected value from the MVVM-file. But eventhough I set the selected value when I create the MVVM-object, the value is not set when the combo box is shown:
<ListBox ItemsSource="{Binding Maintenances}" removed="Transparent" BorderThickness="0" ItemContainerStyleSelector="{StaticResource ListBoxItemStyleSelector}" VerticalAlignment="Bottom">
<ListBox.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Text="{Binding Type.Name}" VerticalAlignment="Bottom" FontWeight="Bold" Width="100">
</TextBlock>
<ComboBox ItemsSource="{Binding Centers,Mode=OneTime}" Width="250"
Style="{StaticResource ComboBoxTransparentStyle}"
SelectedItem="{Binding SelectedType,Mode=TwoWay}"
DisplayMemberPath="Name" SelectedValuePath="Name" />
</WrapPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
从非解决方案复制的其他信息
更改组合框时,mvvm对象中的选定值文件已正确更新
additional information copied from non-solution below
The selected value files in the mvvm object is correctly updated when I change the combobox
推荐答案
嘿pjank42,
只需从ComboBox中删除SelectedValuePath =Name,即全部:-)
您正在尝试绑定Name属性(可能类型字符串)到SelectedType变量,它是MaintenanceCenterMVVM。
Hey pjank42,
just remove SelectedValuePath="Name" from the ComboBox, that's all :-)
You're trying to bind the Name Property (probably of type string) into the SelectedType variable which is a MaintenanceCenterMVVM.
这篇关于WPF中的双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!