2014-12-13 66 views
1

我在我的viewmodel中有兩個屬性,名爲PremisesTowns。 我將我的ListViewItems綁定到Premises,並且在項目模板中我想綁定到Towns,但是當我使用以下XAML時,它嘗試綁定到Premises.Towns而不是Towns綁定到第二個屬性

如何直接綁定到Towns

視圖模型:

public class MainWindowViewModel 
{ 
    public ObservableCollection<Premise> Premises; 
    public List<Town> Towns; 
} 

XAML:

<ListView x:Name="PremisesList" Margin="195,35,10,10" 
       ItemContainerStyle="{StaticResource OverviewListViewItemStyle}" 
     ItemsSource="{Binding Premises}" HorizontalContentAlignment="Stretch"> 

而且這是在我的OverviewListViewItemStyle

<ComboBox ItemsSource="{Binding Towns}" Grid.Row="2" Grid.ColumnSpan="3"> 
     <ComboBox.ItemTemplate> 
      <DataTemplate> 
       <ComboBoxItem> 
        <TextBox Text="{Binding Name}" /> 
       </ComboBoxItem> 
      </DataTemplate> 
     </ComboBox.ItemTemplate> 
    </ComboBox> 

我希望能夠選擇一個Town爲通過XAML一個Premise

+0

問題在哪裏?它不顯示'Towns'或者你不知道如何選擇'Town'作爲'Premise'? – dkozl 2014-12-13 09:32:15

+0

@dkozl我沒有在我的組合框中看到任何「Towns」。我懷疑這是因爲WPF正在尋找'Premises.Towns'屬性,它不存在,因此沒有顯示數據。 – 2014-12-13 09:34:05

+0

@dkozl你是否也碰巧知道要採取的步驟,以便我可以輕鬆地選擇一個鎮的前提? – 2014-12-13 09:44:18

回答

2

你的假設是正確的。 ComboBoxPremise類中尋找Towns類,它是每個後面的類ListViewItem如果要引用與ListView相同的上下文,則需要使用RelativeSource綁定。

<ComboBox 
    ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.Towns}" 
    Grid.Row="2" 
    Grid.ColumnSpan="3" 
    DisplayMemberPath="Name"/> 

不相關的問題,但你也不需要指定DataTemplate顯示單個屬性。 DisplayMemberPath也可以工作。如果您指定DataTemplate你不需要使用ComboBoxItem作爲ComboBox將包裝DataTemplate內容ComboBoxItem如此有效地你會ComboBoxItem最終內的另一個ComboBoxItem

+0

事實上,這是訣竅。感謝您的快速幫助!現在想出顯示> 2500項目的性能問題。 – 2014-12-13 09:41:15

+0

您是否在'ComboBox'中看到2500+項目的任何性能問題? – dkozl 2014-12-13 09:49:31

+0

我在點擊組合框和看到項目之間看到5-7秒的延遲。 – 2014-12-13 10:00:16

1

您綁定的ItemsSource的處所財產因此,如果您綁定到在OverviewListViewItemStyle的Towns中,綁定引擎將在Premise對象中查找名爲Towns的屬性。 如果你想選擇一個房屋的小鎮,你應該告訴組合框在那裏看那個房產。您可以嘗試將組合框的datacontext設置爲綁定中相對源的主視圖模型。類似的東西: ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.Towns}"