ティッカーの表示テキストを表す単純な Text プロパティを持つ TickerUserControl があります。
これらの DependencyProperty パターンを UserControl 内で本当に使用する必要がありますか (以下を参照)、またはこれを実現するためのより簡単な方法はありますか?
UserControl を使用し、テキスト フィールドを ViewModel のプロパティに BIND する場合、次の奇妙なバインディング構文を使用する必要があります。他のすべてのコントロールのように 'Text="{Binding Text}"' を使用できないのはなぜですか? UserControl のプロパティの実装などに問題がありますか?
ユーザーコントロールの使用
<userControls:TickerUserControl Text="{Binding Path=Parent.DataContext.TickerText, RelativeSource={RelativeSource Self}, Mode=OneWay}"/>
UserControl のプロパティ実装 (分離コード)
public partial class TickerUserControl : UserControl
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(TickerUserControl), new PropertyMetadata(""));
// ...
}
UserControl の XAML スニペット
<UserControl x:Class="Project.UserControls.TickerUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
mc:Ignorable="d">
<TextBlock Text="{Binding Text}">
<!-- ... -->
ソリューション
問題は、UserControl 内の DataContext の設定でした。DataContext バインディングを削除して、UserControl に名前を追加し、UserControl 内の TextBox バインディングを変更しました。その後は外から「いつも通り」バインドできました。
<userControls:TickerUserControl Text="{Binding TickerText}"/>
<UserControl x:Class="Project.UserControls.TickerUserControl"
Name="TickerUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<TextBlock Text="{Binding Text, ElementName=TickerUserControl}">
<!-- ... -->