簡體   English   中英

綁定到WPF組合框的“ SelectedItem”的屬性的奇怪行為

[英]Weird behavior for a property bound to the 'SelectedItem' of a WPF Combobox

將屬性綁定到WPF組合框的SelectedItem時,我希望每次更改組合框的選擇時都會看到該屬性設置器被調用。 我沒看到

更改選擇時,組合框是否應調用綁定的SelectedItem的屬性設置器?

另外 :實際上,我在那里部分綁定了:第一次加載/選擇組合框時,調用屬性getter,並且調用屬性setter一次,以后再更改選擇時就不再調用。

我注意到的一件事是,當我在Xaml的組合框條目中添加IsSynchronizedWithCurrentItem = True ,在組合框加載/初始選擇時將調用一次setter,但不會再調用一次。 當我刪除該組合框屬性時,setter 永遠不會被調用。 很奇怪。

另外,我指的是視圖模型屬性,而不是依賴項屬性。 至少我沒有將其設置為依賴項屬性。 我是新來的(驚喜!),因此,更多有關此主題的信息將不勝感激。

xaml代碼:

<ComboBox MinWidth="300" Margin="5,0,0,5"
   ItemsSource="{Binding KeywordCollectionTypes, Mode=OneWay}"
   SelectedItem="{Binding KeywordCollectionType, Mode=TwoWay}"
   IsSynchronizedWithCurrentItem="True"/>

ViewModel代碼(綁定屬性):

 public Collection<string> KeywordCollectionTypes
    {
        get
        {
            return _KeywordCollectionTypes;
        }
    }

public string KeywordCollectionType
    {
        get
        {
            return _KeywordCollectionType;
        }
        set
        {
            _KeywordCollectionType = value;

            OnPropertyChanged("KeywordCollectionType");
        }
    }

還有一點信息是,組合框位於DataGrid.RowDetailsTemplate ,那么這種奇怪的更新行為可能與它位於行詳細信息中有關嗎?

我終於弄清楚了我遇到的問題。 在對組合框的SelectedItem的綁定語句中,我需要輸入:“ UpdateSourceTrigger = PropertyChanged”

像這樣:

<ComboBox MinWidth="300" Margin="5,0,0,5"
                                      ItemsSource="{Binding KeywordCollectionTypes, Mode=OneWay}"
                                      SelectedItem="{Binding KeywordCollectionType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

這是使我得以解決的線程:

將數據綁定(使用MVVM模式)到DataGrid的RowDetailsTemplate中的WPF組合框的問題

您做錯了。 從我當前的項目中:

<ComboBox
   ItemsSource="{Binding Configurations}" 
   SelectedItem="{Binding SelectedConfiguration, Mode=TwoWay}"/>

每次更改所選項目時,都會調用SelectedConfiguration屬性設置器。

編輯

我假設您的對象不是DependencyObject ,並且綁定到的屬性不是依賴項屬性。 如果它是一個依賴屬性,那么正如DK所觀察到的,綁定將通過調用SetValue來更新屬性值,並繞過CLR屬性訪問器; 如果要在該控制流中插入邏輯,請在注冊依賴項屬性時引用一個回調方法。

這是將組合框的選定項綁定到數據模型的方式。

 <ComboBox SelectedItem="{Binding Path=MyValue}"/>

其中MyValue是您的DataContext / Data模型的屬性。

如果要將其他控件(例如TextBlock)綁定到所選項目,這是一個小示例...

<ComboBox Name="myComboBox" SelectedIndex="0">
   <ComboBoxItem>1</ComboBoxItem>
   <ComboBoxItem>2</ComboBoxItem>
   <ComboBoxItem>3</ComboBoxItem>
</ComboBox>
<TextBlock Text="{Binding ElementName=myComboBox, Path=SelectedItem.Content}"/>

在這里,只要組合框選擇更改,文本塊就會更新。

暫無
暫無

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

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