2017-01-20 41 views
0

我有一個數據網格,組合框列的讀取模式,定義爲:如何呈現在DataGridComboBoxColumn文本,該行

   <!-- Category --> 
       <DataGridComboBoxColumn Header="Category" SelectedValueBinding="{Binding SelectedCategory}" DisplayMemberPath="DisplayName"> 
        <!-- Display mode --> 
        <DataGridComboBoxColumn.ElementStyle> 
         <Style TargetType="{x:Type ComboBox}"> 
          <Setter Property="Text" Value="{Binding SelectedCategoryDisplayName}" /> 
         </Style> 
        </DataGridComboBoxColumn.ElementStyle> 

        <!-- Edit mode --> 
        <DataGridComboBoxColumn.EditingElementStyle> 
         <Style TargetType="{x:Type ComboBox}"> 
          <Style.Triggers> 
           <DataTrigger Binding="{Binding Transaction.Type}" Value="Debit"> 
            <Setter Property="ItemsSource" Value="{Binding Source={StaticResource debitCategories}}" /> 
           </DataTrigger> 
           <DataTrigger Binding="{Binding Transaction.Type}" Value="Credit"> 
            <Setter Property="ItemsSource" Value="{Binding Source={StaticResource creditCategories}}" /> 
           </DataTrigger> 
          </Style.Triggers> 
         </Style> 
        </DataGridComboBoxColumn.EditingElementStyle> 
       </DataGridComboBoxColumn> 

它是由視圖模型屬性的支持:

public string SelectedCategoryDisplayName 
    { 
     get 
     { 
      return "something"; 
     } 
    } 

在設計,這是給我下面的錯誤:

A TwoWay or OneWayToSource binding cannot work on the read-only property 'SelectedCategoryDisplayName' of type XXX 

爲什麼?爲什麼WPF在使用DataGridComboBoxColumn.ElementStyle時關心該屬性是隻讀的。如果我理解正確,DataGridComboBoxColumn.ElementStyle是單元格讀取模式的樣式。

好的,所以我在綁定上設置了,Mode=OneWay,它停止了抱怨,但它沒有顯示任何內容。

如何在單元格/行的讀取模式(非編輯)下使我的View Model提供的組合框顯示文本?

回答

1

Why? Why does WPF care that the property is read-only, when it is used in the DataGridComboBoxColumn.ElementStyle.

因爲您綁定到ComboBox的Text屬性,並且此屬性默認是雙向的。要麼源屬性必須有公共setter,要麼您需要將綁定的模式設置爲OneWay。

How do I make the Combo Box show text provided by my View Model, in the read mode (non-edit) of the cell/row?

試試這個:

<DataGridComboBoxColumn.ElementStyle> 
    <Style TargetType="{x:Type ComboBox}"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate> 
        <TextBlock Text="{Binding SelectedCategoryDisplayName, Mode=OneWay}"/> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</DataGridComboBoxColumn.ElementStyle> 
+0

謝謝您的回答。但是,代碼段不起作用。事實上'SelectedCategoryDisplayName'屬於'T'。我可以在被調用的調試器中看到它。但是用戶界面仍然沒有顯示任何文本塊應該顯示的位置。可以'「是否搞亂了它? –

+1

對不起。我編輯了我的答案。 – mm8

+0

再一次 - 我的救世主;) –