基于其他控件的Gotfocus事件显示控件的文本

3

我刚接触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个回答

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

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

感谢您发布示例代码。它的工作很好。 如果我有多个控件(ComboBox、TextBox等),那么如何将所有控件的工具提示绑定到一个TextBlock,基于特定控件的GotFocus()事件? - Hebbar
我正在使用MVVM模式将控件绑定到模型。如果我没错的话,附加的这段代码违反了MVVM模式? - Hebbar
感谢您的回复,通过您提供的代码,我成功地得到了所需的答案。 - Hebbar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接