1

ティッカーの表示テキストを表す単純な Text プロパティを持つ TickerUserControl があります。

  1. これらの DependencyProperty パターンを UserControl 内で本当に使用する必要がありますか (以下を参照)、またはこれを実現するためのより簡単な方法はありますか?

  2. 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}">

        <!-- ... -->
4

2 に答える 2

1
  1. のコード ビハインドでバインド可能なプロパティを作成する場合は、UserControlオブジェクト使用する必要がありDependencyPropertyます。ただし、そこにバインド可能なプロパティを作成する必要はありません... MVVM 型パターンを使用して、バインド可能なプロパティを別のクラスに作成することできDataContextますUserControl

  2. いいえ、その「奇妙な」バインディング構文を使用する必要はありません...問題は、コードビハインドへの設定DataContextをハードコーディングしていることです。UserControlそれを行う代わりに、次Text DependencyPropertyのようにコントロールにバインドできます。

    <TextBlock Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, 
    {AncestorType={x:Type Local:TickerUserControl}}}" />
    

Localは、ローカル プロジェクトの XML 名前空間です...次のようなものです。

     xmlns:Local="clr-namespace:Project.UserControls.TickerUserControl"

その後、バインドを削除した後、DataContext通常どおり外部からコントロールにバインドできるようになります。

于 2013-08-14T08:40:04.310 に答える