我想知道是否可以将listviewitem绑定到Listview
的Item模型的静态字段。
以下是伪代码。
model
{
public string name {get; set;}
public string age {get; set;}
public static ObservableCollection<string> recommended_schoolNames {get; set;}
public string schoolName {get; set;}
}
然后,在xaml中,我像这样设置属性。
`ListView` ItemSources = ObservableCollection<model> data;
<DataTempate>
`ListviewItem1` <TextBox Text={Binding age}> //works good
`ListviewItem2` <TextBox Text={Binding name}> // works good
then, I need to show combo box to user can select school from recommended_schoolNames.
<ComboBox .... ItemsSource={Binding recommended_schoolName}>.
</DataTemplate>
我很好,如果您提出其他解决方案来解决此问题。
我曾考虑将静态observablecollection<string>
从模型移动到视图模型的ObservableCollection<string>
,但是未能在Listview Itemtemplate引用Viewmodel属性中设置组合框的Item source。
对我英语水平不佳感到抱歉。感谢您阅读本文。
正如Christoper所建议的,我试图将静态ObservableCollection从模型类移动到viewModel的ObservableCollection。
但是失败了..以下是我的消息来源。
viewmodel{
public ObservavbleCollection <model> myModel {get; set;}
public ObservableCollection<string> nnames { get; set; }
}
<ListView
x:Name="VariableListView"
Grid.Row="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
Background="Transparent"
ItemContainerStyle="{DynamicResource ListViewItemStyle}"
ItemsSource="{Binding variableModels}"
SelectedItem="{Binding selectedItem}"
SelectionMode="Extended"
Style="{DynamicResource VariableListViewStyle}">
<ListView.ItemTemplate>
<DataTemplate>
<ComboBox
x:Name="DefaultValueCombobox"
Grid.Column="2"
Width="147"
Height="24"
Margin="12,0,0,0"
DataContext="{Binding Source={x:Reference Name=variableUserControl}, Path=DataContext}"
Foreground="#FFEAEAEA"
ItemContainerStyle="{DynamicResource gridViewComboBoxItemStyle}"
ItemsSource="{Binding nnames}"
SelectedItem="{Binding DefaultValue}"
Style="{DynamicResource VariableComboBoxStyle}" />
答案 0 :(得分:0)
我通过设置控制数据上下文解决了。
<ComboBox
x:Name="DefaultValueCombobox"
Grid.Column="2"
Width="147"
Height="24"
Margin="12,0,0,0"
DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext}"
Foreground="#FFEAEAEA"
ItemContainerStyle="{DynamicResource gridViewComboBoxItemStyle}"
ItemsSource="{Binding nnnames}"
SelectedItem="{Binding DefaultValue}"
Style="{DynamicResource VariableComboBoxStyle}" />
我在此之前尝试过,但是失败了。我找到了原因。
当时我没有分配ObservableCollection<string>
。 -_- ..
我没注意到Visual Studio的输出控制台...
我完成了如下工作。我使用RelativeSource
绑定数据。
<ComboBox
x:Name="DefaultValueCombobox"
Grid.Column="2"
Width="147"
Height="24"
Margin="12,0,0,0"
Foreground="#FFEAEAEA"
ItemContainerStyle="{DynamicResource gridViewComboBoxItemStyle}"
ItemsSource="{Binding Path=DataContext.nnnames, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
SelectedItem="{Binding DefaultValue}"
Style="{DynamicResource VariableComboBoxStyle}" />