0

我有以下代码:XAML:

<UserControl x:Class="RBSoft.WPF.RedConsoleViewer"
             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" 
             d:DesignHeight="355" d:DesignWidth="691" Name="ConsoleUI_Control" KeyDown="ConsoleUI_Control_KeyDown">
    <Grid Name="_Layout">
        <Rectangle Name="BackgroundLayout">
            <!--...-->
        </Rectangle>
    </Grid>
</UserControl>

代码:

public Rectangle IBackground
{
    get { return this.BackgroundLayout; }
    set { this.BackgroundLayout = value; }
}

我要做的是从 XAML 编辑器中编辑矩形(BackgroundLayout),如下所示:

<Window x:Class="LifeEnvironment.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="1064" Width="910"
        xmlns:my="clr-namespace:RBSoft.WPF;assembly=RBSoft.WPF"
        WindowStyle="None"
        WindowState="Maximized"
        WindowStartupLocation="CenterScreen">
    <Grid>
        <my:userControlTest>
            <my:userControlTest.IBackground>
                <Background ...>
            </my:userControlTest.IBackground>
        </my:userControlTest>
    </Grid>
</Window>

但是我无法访问这个,我需要做什么?

4

2 回答 2

1

正确的做法是用用户控件包裹矩形,如下所示:

<UserControl x:Class="RBSoft.WPF.RedConsoleViewer" ...>
    <Grid Name="_Layout">
        <UserControl Name="BackgroundLayout">
            <Rectangle .../>
        </UserControl>
    </Grid>
</UserControl>

然后,更改Content属性而不是对象本身,这样就不会丢失引用(BackgroundLayout):

public Rectangle IBackground
{
    get { return (Rectangle)this.BackgroundLayout.Content; }
    set { this.BackgroundLayout.Content = value; }
}

最后,它将起作用:

<my:userControlTest>
    <my:userControlTest.IBackground>
        <Background ...>
    </my:userControlTest.IBackground>
</my:userControlTest>
于 2012-05-08T14:03:26.207 回答
0
  • 为了能够访问 XAML 中的控件属性,您需要将其设置为依赖属性。

  • 我认为(至少从我所见)一种更常见的方法来做你想做的事情是使用控制内部矩形背景的“通用”样式。

    编辑

    public static readonly DependencyProperty IBackgroundProperty = DependencyProperty.Register("IBackground", typeof(Rectangle), typeof(NameOfYourUserControl));
    public Rectangle IBackground
    {
        get { return (Rectangle)GetValue(IBackgroundProperty); }
        set { SetValue(IBackgroundProperty, value); }
    }
    

更改为依赖属性将使您的 XAML 编译,但是,您仍然必须在用户控件中处理它。

此外,当您使用它时,您正在尝试将背景设置为矩形类型的属性!那显然行不通。您必须实例化您的属性是什么 - 一个矩形:

<my:userControlTest>
        <my:userControlTest.IBackground>
            <Rectangle  Fill="Orange"/>
        </my:userControlTest.IBackground>
    </my:userControlTest>
于 2012-05-04T15:21:37.400 回答