簡體   English   中英

在WPF中對DataGrid的TwoWay綁定ObservableCollection不起作用

[英]TwoWay Binding ObservableCollection to DataGrid in WPF not working

我在我的應用程序中有這個簡單的DataGrid。 在源代碼的某處,我將它的ItemsSource屬性綁定到ObservableCollection<System.Windows.Points> 所以這些點顯示在DataGrid 問題是我設置了TwoWay綁定但是當改變DataGrid的點坐標值時, ObservableCollection中的實際點值不會改變!

出了什么問題?

<DataGrid Name="pointList" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="X" Width="200">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=X, Mode=TwoWay}"></TextBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Y" Width="200">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Y, Mode=TwoWay}"></TextBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

注意我已經看到了這個,但我的問題是不同的。

System.Windows.Points是一個結構 您無法正確綁定其屬性。

為什么? 因為當你執行Text="{Binding X, Mode=TwoWay}"它會將TextBoxText屬性綁定到當前DataContextX屬性。

DataContext是...一個struct System.Windows.Points然后數據綁定將修改的Point不是你分配給DataContext那個。

解決你的問題。 使用創建自己的Point類型:

public class Point : INotifyPropertyChanged
{
    private double x;
    public double X
    {
        get { return x; }
        set
        {
            if (x != value)
            {
                x = value;
                OnPropertyChanged("X");
            }
        }
    }
    private double y;
    public double Y
    {
        get { return y; }
        set
        {
            if (y != value)
            {
                y = value;
                OnPropertyChanged("Y");
            }
        }
    }

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

並使用UpdateSourceTrigger=LostFocus進行綁定:

<TextBox Text="{Binding Path=Y, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"></TextBox>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM