1

このコードは正しく動作します:

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

しかし、このコードは機能しません!!!

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

カスタム ツールチップを作成して CustomToolTip にバインドする必要がありますが、何にもバインドされていない 2 番目のコードでは、どこに問題がありますか?

4

1 に答える 1

2

まず第一に、ここで WPF について話しているのであれば、 にはプロパティがないため、<ToolTip Content="...">の代わりにする必要があります。<ToolTip Text="...">ToolTipText

バインディングについて: ToolTip 要素はビジュアル ツリーの一部ではないため、ToolTip 内からユーザー コントロール内の他の要素へのバインドは機能しませ

ただし、UserControl のコード ビハインドで定義されているプロパティにバインドしているようです。その場合、UserControlDataContextをコントロール自体に設定することで、さらに簡単に解決できます。

<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

CustomToolTipさらに良い解決策は、およびすべての同様のプロパティを保持する一種の Viewmodel クラスを導入し、このクラスを UserControl の として設定することDataContextです。

于 2014-08-01T08:22:42.900 に答える