2

次のような依存関係プロパティを持つユーザー コントロールを実装しました。

public partial class MyUC : UserControl, INotifyPropertyChanged
{
    public static readonly DependencyProperty MyBackgroundProperty =
        DependencyProperty.Register("MyBackground", typeof(Brush), typeof(MyUC), 
            new FrameworkPropertyMetadata(Brushes.White, 
                FrameworkPropertyMetadataOptions.AffectsRender));

    public Brush MyBackground
    {
        get { return (Brush)GetValue(MyBackgroundProperty); }
        set { SetValue(MyBackgroundProperty, value); }
    }

    //...
}

次のように XAML でこのプロパティを設定してみてください。

<UserControl x:Class="Custom.MyUC"
         x:Name="myUCName"
         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" 
         xmlns:local="clr-namespace:Custom"
         mc:Ignorable="d"
         TabIndex="0" KeyboardNavigation.TabNavigation="Local" 
         HorizontalContentAlignment="Left" VerticalContentAlignment="Top" 
         MouseLeftButtonDown="OnMouseLeftButtonDown"> 
    <UserControl.Style>
        <Style TargetType="local:MyUC">      
            <Setter Property="MyBackground" Value="Black"/>
        </Style>
    </UserControl.Style>   

    <Border BorderThickness="0">
        //...
    </Border>
</UserControl>

コンパイルされますが、アプリを実行すると次の例外が発生します。

プロパティ 'System.Windows.Setter.Property' を設定すると、例外がスローされました。行番号 '..' および行位置 '..'."

どうすればこれを解決できますか?

4

1 に答える 1

1

この問題は、タイプ UserControl の要素に TargetType="MyUC" のスタイルを適用しようとしているために発生します。

解決策は、コントロールの外側からスタイルを適用することです。たとえば、別のウィンドウでコントロールを使用する場合:

<Window.Resources>
    <Style TargetType="local:MyUC">
        <Setter Property="MyBackground" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <local:MyUC />
</Grid>

テストとして、次のコードをユーザー コントロールに追加しました。

public partial class MyUC
{
    public MyUC()
    {
        InitializeComponent();
    }   

    public static readonly DependencyProperty MyBackgroundProperty =
        DependencyProperty.Register("MyBackground", typeof(Brush), typeof(MyUC), 
        new PropertyMetadata(Brushes.White, PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject dependencyObject, 
        DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        ((MyUC)dependencyObject).MyBackgroundPropertyChanged(
            (Brush)dependencyPropertyChangedEventArgs.NewValue);
    }

    private void MyBackgroundPropertyChanged(Brush newValue)
    {
        Background = newValue;
    }

    public Brush MyBackground
    {
        get { return (Brush)GetValue(MyBackgroundProperty); }
        set { SetValue(MyBackgroundProperty, value); }
    }
}

その結果、コントロールの背景が赤くなります。

于 2013-04-06T16:03:29.927 に答える