gpt4 book ai didi

wpf - 无法转换值 ''。具有无效的 SelectedValue 和空源

转载 作者:行者123 更新时间:2023-12-01 12:54:36 26 4
gpt4 key购买 nike

当我第一次加载窗口时,Combobox 在绑定(bind)时显示验证错误消息“无法转换值”SelectedValue="{Binding ID, ElementName=mySelf, Mode=TwoWay}...调用 UpdateTarget() 验证错误消失。在这两种情况下,ID 都是 0,它绑定(bind)到 SelectedValue 属性(Load 和 ButtonClick)

我看到的唯一区别是 Employees 集合是在 InitializeComponents 之后加载的(如果我在 InitializeComponents 验证错误消失之前添加它)

public class Employee
{
public Employee(Int32 id, String name)
{
this.ID = id;
this.Name = name;
}
public int ID { get; set; }

public string Name { get; set; }
}

XAML

<Grid>
<ComboBox VerticalAlignment="Center" Margin="12,57,424,93" x:Name="cmbEntityBuyer2" Width="230"
ItemsSource="{Binding Employees, ElementName=mySelf}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValue="{Binding ID, ElementName=mySelf, Mode=TwoWay}"
IsEditable="False"/>

<TextBox Text="{Binding ElementName=cmbEntityBuyer2,Path=SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Height="25" Margin="12,12,424,134" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,108,0,0" Name="button1" VerticalAlignment="Top" Width="230" Click="button1_Click" />
</Grid>

代码隐藏

 public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
Employees.Add(new Employee(1, "Vinay"));
Employees.Add(new Employee(2, "Leny"));
}

Int32 _id = 0;
public Int32 ID
{
get { return _id; }
set { _id = value; OnPropertyChanged("ID"); }
}

ObservableCollection<Employee> _emp = new ObservableCollection<Employee>();
public ObservableCollection<Employee> Employees
{
get { return _emp; }
set { _emp = value; }
}

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}

private void button1_Click(object sender, RoutedEventArgs e)
{
String error = Validation.GetErrors(cmbEntityBuyer2)[0].ErrorContent.ToString();
cmbEntityBuyer2.GetBindingExpression(ComboBox.SelectedValueProperty).UpdateTarget();
}
}

最佳答案

尝试在绑定(bind)中使用 TargetNullValue=''

this link

关于wpf - 无法转换值 ''。具有无效的 SelectedValue 和空源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10518138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com