簡體   English   中英

SelectedItem 事件在 LostFocus 更新源之前觸發

[英]SelectedItem event fire before LostFocus to update source

我有一段代碼將 Collection 綁定到 DataGrid,並且選擇 DataGrid 將允許在 TextBoxes 中進行詳細編輯。

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

這里的問題是當在 TextBoxes 中編輯某些內容時(比如在文本框中添加一個字符,而不會失去焦點),然后 select 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>

您可以在已編輯的文本框的離開事件中添加和邏輯。 這應該在數據網格獲得焦點之前觸發。

暫無
暫無

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

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