3

我的应用程序中有这个简单的 DataGrid。在源代码的某个地方,我将ItemsSource它的属性绑定到一个ObservableCollection<System.Windows.Points>. 所以点显示在DataGrid. 但是问题是我已经设置了TwoWay绑定,但是当更改 中的点坐标值时DataGrid,实际点值 intObservableCollection没有改变!

出了什么问题?

<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>

注意我已经看到了,但我的问题是不同的。

4

1 回答 1

1

System.Windows.Points is a struct. You can't bind its properties correctly.

Why? Because when you do Text="{Binding X, Mode=TwoWay}" it will bind the Text property of the TextBox to the X property of the current DataContext.

DataContext which is... a struct System.Windows.Points then the Point the databinding will modify is not the one you have assigned to DataContext.

To solve your problem. Create your own Point type using a class:

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));
    }
}

and use UpdateSourceTrigger=LostFocus for your binding:

<TextBox Text="{Binding Path=Y, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"></TextBox>
于 2013-01-30T15:27:51.853 回答