在LostFocus更新源之前,SelectedItem事件触发

时间:2012-04-04 13:39:36

标签: c# wpf silverlight xaml triggers

我有一段将Collection绑定到DataGrid的代码,而DataGrid的选择将允许在TextBox中进行详细编辑。

所以基本上DataGrid绑定到Collection,TextBoxes绑定到DataGrid.SelectedItem。(properties)。

这里的问题是在TextBoxes中编辑某些内容(比如在文本框中添加一个字符而不会丢失焦点),然后在DataGrid中选择另一个项目(现在丢失焦点)。 DataGrid将更新它的SelectedItem属性,但是现在假设对前一项进行的更改消失了,当丢失的焦点事件发生时,PropertyChanged事件不会触发。

我知道我可以使用UpdateTriggerSource=PropertyChanged来解决它,但是如果我使用PropertyChanged,会发生很多事件,所以我想知道是否有解决方案来解决这个问题

以下是我可以重现此问题的示例代码:

代码隐藏:

public partial class MainPage : UserControl
{
    Person _SelectedPerson { get; set; }
    public Person SelectedPerson
    {
        get
        {
            return this._SelectedPerson;
        }
        set
        {
            if (this._SelectedPerson == value)
                return;
            this._SelectedPerson = value;
        }
    }

    public MainPage()
    {
        InitializeComponent();

        Person personA = new Person() { FirstName = "Orange", LastName = "Cake" };
        Person personB = new Person() { FirstName = "Apple", LastName = "Pie" };
        ObservableCollection<Person> aPersonCollection = new ObservableCollection<Person>();
        aPersonCollection.Add(personA);
        aPersonCollection.Add(personB);

        MyDataGrid.ItemsSource = aPersonCollection;
        this.DataContext = this;
    }
}

public class Person : INotifyPropertyChanged
{
    string _LastName { get; set; }
    public string LastName
    {
        get
        {
            return this._LastName;
        }
        set
        {
            if (this._LastName == value)
                return;
            this._LastName = value;
            this.OnPropertyChanged("LastName");
        }
    }

    string _FirstName { get; set; }
    public string FirstName
    {
        get
        {
            return this._FirstName;
        }
        set {
            if (this._FirstName == value)
                return;
            this._FirstName = value;
            this.OnPropertyChanged("FirstName");
        }
    }

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

XAML:

<Grid x:Name="LayoutRoot" Background="White">
    <StackPanel>
        <sdk:DataGrid x:Name="MyDataGrid" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}" />
        <TextBox Text="{Binding SelectedItem.FirstName, ElementName=MyDataGrid, Mode=TwoWay}" />
        <TextBox Text="{Binding SelectedItem.LastName, ElementName=MyDataGrid, Mode=TwoWay}" />
    </StackPanel>            
</Grid>

1 个答案:

答案 0 :(得分:0)

您可以为已编辑的文本框的leave事件添加和逻辑。这应该在数据网格获得焦点之前触发。