数据绑定不显示值

时间:2015-08-17 17:59:08

标签: wpf vb.net mvvm data-binding

我有一个标签控件,可以在加载时加载标签页和内容。我的所有逻辑都正常工作并正确生成外观和样式,但我的数据都不是数据绑定。

TabControl.xaml

<Grid>
    <ScrollViewer>
        <TabControl ItemsSource="{Binding Tabs}"
                    SelectedIndex="0"
                    ContentTemplate="{StaticResource templateForTheContent}"
                    ItemTemplate="{StaticResource templateForTheHeader}">
        </TabControl>
    </ScrollViewer>
</Grid>

<DataTemplate x:Key="templateForTheContent" >
    <ItemsControl ItemsSource="{Binding Fields}" ItemTemplateSelector="{StaticResource templateSelector}" />
</DataTemplate>

<local:MyDataTemplateSelector x:Key="templateSelector"
                              TextBoxDataTemplate="{StaticResource TextBoxDataTemplate}"
                              ComboBoxDataTemplate="{StaticResource ComboBoxDataTemplate}" 
                              MultiValueDataTemplate="{StaticResource MultiValueDataTemplate}"/>

<StackPanel>
    <Label Content="{Binding Path=Caption, Mode=TwoWay}" ></Label>
    <ComboBox  Margin="8,0" ItemsSource="{Binding Value}" HorizontalAlignment="Stretch" Name="ComboBox1" SelectedIndex="0">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="DropDownOpened">
                <i:InvokeCommandAction Command="{Binding Path=DropDownOpened}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ComboBox>
</StackPanel>

我的控件绑定到TabViewModel

Public Property Tabs As ObservableCollection(Of dmsTab)

我的dmsTab

Public Property Fields As ObservableCollection(Of FieldViewModel)

FieldViewModel.vb

Public Property Field As Field

我的Field有我正在尝试Databind的Caption和value属性。这是我应该怎么做的?或者有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

使用DataTemplate中的{Binding}语法并不是那样的,因为它没有正确的DataContext。我做了类似的事情:

{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type xxx}}, Path=blah}

在我的DataTemplates中,它可以正常工作。

答案 1 :(得分:0)

我认为你的DataContext层次结构中有一个额外的级别

根据您发布的代码,您的XAML绑定正在尝试在

中找到该属性
Tabs[X].Fields[N].Caption

但是你的代码结构是

Tabs[X].Fields[N].Field.Caption

尝试更改绑定以包含Field属性,如下所示:

<StackPanel>
    <Label Content="{Binding Path=Field.Caption}" />
    <ComboBox ItemsSource="{Binding Field.Value}" SelectedIndex="0">
        ...
    </ComboBox>
</StackPanel>

或者,如果您的模板很复杂并且有很多绑定,您可以设置整个StackPanel的DataContext

<StackPanel DataContext="{Binding Field}">
    <Label Content="{Binding Path=Caption}" />
    <ComboBox ItemsSource="{Binding Value}" SelectedIndex="0">
        ...
    </ComboBox>
</StackPanel>
相关问题