根据其他控件的Gotfocus显示Control的文本

时间:2012-05-02 10:18:26

标签: c# wpf mvvm combobox

我是WPF开发的新手。

我正在使用MVVM模式开发一个wpf应用程序。我有一个'ComboBox'和'TextBlock'控件。在对ComboBox进行聚焦时,Textblock应显示Combobox的工具提示。 Combobox被绑定以查看模型。

<ComboBox Name="cmbSystemVoltage" 
          ToolTip="RMS value of phase-phase voltage in kV" 
          ItemsSource="{Binding Path=SystemVoltageStore}"
          SelectedItem="{Binding Path=SelectedSystemVoltage}" 
          DisplayMemberPath="SystemVoltageLevel"/>

我怎样才能做到这一点。这样做的示例代码将非常有用。

谢谢, Sudhi

1 个答案:

答案 0 :(得分:2)

使用DataTrigger并按ElementName绑定:

<StackPanel>
    <TextBlock>
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}">                   
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=cmbSystemVoltage, Path=IsKeyboardFocusWithin}"
                                 Value="True">
                        <Setter Property="Text"
                                Value="{Binding ElementName=cmbSystemVoltage, Path=ToolTip}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
    <ComboBox Name="cmbSystemVoltage" ToolTip="RMS value of phase-phase voltage in kV" />
</StackPanel>

修改

如果您想在TextBlock中显示多个控件的工具提示,我宁愿订阅PreviewGotKeyboardFocus Event

<Window PreviewGotKeyboardFocus="Window_PreviewGotKeyboardFocus">
    <StackPanel>
        <TextBlock x:Name="toolTipIndicator" />
        <ComboBox ToolTip="Sample text" />
        <TextBox ToolTip="Other sample text" />
    </StackPanel>
</Window>

void Window_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    FrameworkElement element = e.NewFocus as FrameworkElement;

    if (element != null && element.ToolTip != null)
    {
        this.toolTipIndicator.Text = element.ToolTip.ToString();
    }
    else
    {
        this.toolTipIndicator.Text = string.Empty;
    }
}