1

this code work correct:

   <UserControl x:Class="Extended.InputControls.TextBoxUserControl" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:Extended.InputControls">
        <TextBox x:Name="textBox"
            ToolTip="{Binding Path=CustomToolTip,RelativeSource={RelativeSource AncestorType=local:TextBoxUserControl}}"/>
</UserControl>

but this code Does not work!!!

<UserControl x:Class="Extended.InputControls.TextBoxUserControl" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:Extended.InputControls">
        <TextBox x:Name="textBox">
            <TextBox.ToolTip>
                <ToolTip Text="{Binding Path=CustomToolTip,RelativeSource={RelativeSource AncestorType=local:TextBoxUserControl}}" Background="Yellow"/>
            </TextBox.ToolTip>
        </TextBox>
</UserControl>

i need create custom tooltip and bind it to CustomToolTip but in second code that's not bind to anything where is the problem?

4

1 回答 1

2

首先,如果我们在这里谈论 WPF,它应该是<ToolTip Content="...">而不是<ToolTip Text="...">,因为ToolTip它没有Text属性。

关于绑定:从 ToolTip 中绑定到用户控件中的其他元素不起作用,因为 ToolTip 元素不是可视树的一部分,正如另一个问题中所解释的那样,它也提供了一个潜在的解决方案

但是,您似乎绑定到 UserControl 的代码隐藏中定义的某些属性?DataContext在这种情况下,通过将 UserControl 设置为控件本身更容易解决:

<UserControl x:Class="Extended.InputControls.TextBoxUserControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:Extended.InputControls"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <TextBox x:Name="textBox">
        <TextBox.ToolTip>
            <ToolTip Content="{Binding CustomToolTip}" Background="Yellow"/>
        </TextBox.ToolTip>
    </TextBox>
</UserControl>

或者,您也可以DataContext在代码隐藏中设置:

public TextBoxUserControl()
{
    this.DataContext = this;
    InitializeComponent();
}

在这两种情况下,CustomToolTip都可以直接访问属性而无需RelativeSource绑定。

一个更好的解决方案是引入一种 Viewmodel 类,它包含CustomToolTip所有类似的属性,并将此类设置为 UserControl 的DataContext

于 2014-08-01T08:22:42.900 回答