3

初めてウィンドウをロードすると、バインド時にコンボボックスに検証エラーが表示され、「値 '' を変換できませんでした」というメッセージが表示されます...検証エラーのSelectedValue="{Binding ID, ElementName=mySelf, Mode=TwoWay}呼び出しで消えます。UpdateTarget()どちらの場合も、ID は 0 で、SelectedValue プロパティ (Load および ButtonClick) にバインドされています。

私が見る唯一の違いは、InitializeComponentsの後にEmployeesコレクションがロードされることです(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();
    }
}
4

1 に答える 1

5

TargetNullValue=''バインディングで使用してみる

このリンク

于 2012-06-28T08:28:02.750 に答える