简体   繁体   中英

Can't bind selected item in templated combobox

I have this modified ComboBox:

<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>

What it does is to display a default text when the selected item is null. The ItemsSource works well. And the whole combobox worked well before using the ContentControl. Now I can't bind properly the SelectedItem, even if I change the selection of the combobox the actual object remains as when I initialize it.

I've read that this solves the problem:

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

But it doesn't help to me, what is happening here? Why can't I bind like I did before?

Errr... you might like to take a look at the BindingBase.TargetNullValue Property page on MSDN to solve your original problem of specifying a value to be displayed when the data bound property is null . You would use it like this:

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

There's no point in re-inventing the wheel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM