【问题标题】:Can't bind selected item in templated combobox无法在模板化组合框中绑定所选项目
【发布时间】:2013-09-11 10:36:42
【问题描述】:

我有这个修改过的组合框:

<ContentControl Content="{Binding LoadedFiles}" >
   <ContentControl.ContentTemplate>
      <DataTemplate>
         <Grid>
            <ComboBox x:Name="cb" ItemsSource="{Binding}" Width="150" Margin="5"   SelectedItem="{Binding SelectedFile}" DisplayMemberPath="FileName"/>
            <TextBlock x:Name="tb" Text="Select a file" IsHitTestVisible="False" Visibility="Hidden" Width="150" VerticalAlignment="Center" Margin="10 0 0 0" FontSize="12" FontStyle="Italic" Foreground="#7FFFFFFF" />
         </Grid>
         <DataTemplate.Triggers>
            <Trigger SourceName="cb" Property="SelectedItem" Value="{x:Null}">
               <Setter TargetName="tb" Property="Visibility" Value="Visible"/>
            </Trigger>
         </DataTemplate.Triggers>
      </DataTemplate>
   </ContentControl.ContentTemplate>
</ContentControl>

它的作用是在所选项目为空时显示默认文本。 ItemsSource 运行良好。在使用 ContentControl 之前,整个组合框运行良好。现在我无法正确绑定 SelectedItem,即使我更改了组合框的选择,实际对象仍保持初始化时的状态。

我听说这可以解决问题:

SelectedItem="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedFile}"

但这对我没有帮助,这里发生了什么?为什么我不能像以前那样绑定?

【问题讨论】:

    标签: c# wpf combobox


    【解决方案1】:

    Err...你可能想看看MSDN上的BindingBase.TargetNullValue Property页面来解决你原来的问题,即当数据绑定属性为null时指定要显示的值.你可以这样使用它:

    <ComboBox x:Name="cb" ItemsSource="{Binding}" Width="150" Margin="5"   
        SelectedItem="{Binding SelectedFile, TargetNullValue='Select a file'}" 
        DisplayMemberPath="FileName"/>
    

    重新发明轮子没有意义。

    【讨论】:

    • 谢谢!这真的很棒,但我不知道为什么它不起作用。外观和以前一样(空)。 MSDN 上的示例是文本框,将字符串作为默认值是有意义的。这可能是这里的问题吗? (我正在绑定自定义对象)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多