我有一個ComboBox
需要依賴另一個ComboBox
的值。這部分已經工作,與相關ComboBox
刷新時,如果選擇在獨立ComboBox
一個新值:WPF,綁定到依賴組合框的屬性總是給出初始值
<!-- Independent -->
<ComboBox Height="23" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="2"
x:Name="cbo_product" VerticalAlignment="Center" Width="120"
ItemsSource="{Binding Source={StaticResource productsXml}}"
DisplayMemberPath="@name" SelectedValuePath="@name"
SelectionChanged="cbo_product_SelectionChanged"
SelectedValue="{Binding Path=Product}" />
<!-- Dependent -->
<ComboBox Height="23" HorizontalAlignment="Left" Grid.Row="3" Grid.Column="2"
x:Name="cbo_component" VerticalAlignment="Center" Width="201"
DataContext="{Binding SelectedItem, ElementName=cbo_product}"
ItemsSource="{Binding XPath=Components/Component}"
DisplayMemberPath="@name" SelectedValuePath="@name"
SelectedValue="{Binding Path=Component}"
SelectionChanged="cbo_component_SelectionChanged" />
在這背後的C#類,我有:
public MyUserControlConstructor()
{
MyViewModelInstance= new MyViewModel();
DataContext = MyViewModelInstance;
}
而在MyViewModel
,我有:
public string Component
{
get { return _component; }
set
{
if (value == _component)
{
return;
}
_component = value;
onPropertyChanged(PropertyNames.Component);
}
}
private void onPropertyChanged(PropertyNames fieldName)
{
if (null == PropertyChanged)
{
return;
}
string propertyName = Enum.GetName(typeof(PropertyNames), fieldName);
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
當我改變依賴ComboBox
(組件),它顯示了新的VAL當然,我在我的應用程序中。但是,當我點擊一個導致顯示Component
屬性值的按鈕時,它始終是初始值,而不是我剛纔在ComboBox
中選擇的值。我認爲我的XAML中一定有錯誤。對於C#,我試圖遵循this和this guide的組合。如何將我的依賴項ComboBox
綁定到嵌套在獨立ComboBox
的SelectedItem
中的XML值,但仍會更新我的類中的Component
屬性?
編輯:我懷疑的是,事情是靠不住的,因爲我設置DataContext
的依賴ComboBox
在兩個地方:在XAML首先在C#構造函數中,我的視圖模型,二是DataContext="{Binding SelectedItem, ElementName=cbo_product}"
。
編輯:我一直在構造函數中設置初始值到我的視圖模型類。當我取出Component
屬性的初始值時,即使在更改了從屬ComboBox
中的選定值之後,我仍然從Component
屬性中獲得任何值。這幾乎只是改變了我已經知道的內容:依賴的ComboBox
與獨立的ComboBox
(它從獨立的ComboBox
獲取其數據)綁定,但不是Component
屬性。
編輯:的要求,這裏是我的XML的一個樣本:
<Products xmlns="">
<Product name="Awesomeness">
<Components>
<Component name="Component of Glory"/>
<Component name="Component of Doom"/>
</Components>
</Product>
</Products>
編輯:我猜一個MultiBinding
會使用,看着this和this後。
編輯:好像我應該能夠得到相關ComboBox
無需設置DataContext
工作,只是利用ItemsSource
:
<ComboBox Height="23" HorizontalAlignment="Left" Grid.Row="3" Grid.Column="2"
x:Name="cbo_component" VerticalAlignment="Center" Width="201"
ItemsSource="{Binding ElementName=cbo_product, Path=SelectedItem,
XPath=Components/Component}"
DisplayMemberPath="@name" SelectedValuePath="@name"
SelectedValue="{Binding Path=Component}"
SelectionChanged="cbo_component_SelectionChanged"/>
然而,這不起作用:因ComboBox
是空的,而不是顯示所有的組件名稱。
如果您概述了數據(XML?),會稍微容易一些。 – 2010-08-13 18:48:52
@亨克:正確。用示例更新了我的問題。 – 2010-08-13 18:52:00