簡體   English   中英

無法綁定模板組合框中的所選項目

[英]Can't bind selected item in templated combobox

我有這個修改后的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>

它的作用是在所選項目為null時顯示默認文本。 ItemsSource運作良好。 並且在使用ContentControl之前,整個組合框都運行良好。 現在,即使更改組合框的選擇,我也無法正確綁定SelectedItem,實際對象仍保持初始化時的狀態。

我讀過這可以解決問題:

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

但這對我沒有幫助,這是怎么回事? 為什么我不能像以前那樣綁定?

錯誤...您可能想看看MSDN上的BindingBase.TargetNullValue屬性頁面來解決您的原始問題,即當數據綁定屬性為null時,指定要顯示的null 您可以這樣使用它:

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

重新發明輪子沒有意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM