2012-09-13 9 views
0

我试图在WPF中创建一个对话框类。该类继承自Window并提供一些默认按钮和设置。重新定义WPF中的ContentControl.Content

的实施基本上是这样的:

namespace Commons { 
    public class Dialog : Window { 
    public new UIElement Content { 
     get { return this.m_mainContent.Child; } 
     set { this.m_mainContent.Child = value; } 
    } 

    // The dialog's content goes into this element. 
    private readonly Decorator m_mainContent = new Decorator(); 
    // Some other controls beside "m_mainContent". 
    private readonly StackPanel m_buttonPanel = new StackPanel(); 

    public Dialog() { 
     DockPanel content = new DockPanel(); 

     DockPanel.SetDock(this.m_buttonPanel, Dock.Bottom); 
     content.Children.Add(this.m_buttonPanel); 

     content.Children.Add(this.m_mainContent); 

     base.Content = content; 
    } 

    public void AddButton(Button button) { 
     ... 
    } 
    } 
} 

正如你所看到的,我重新定义了Content财产。

现在我希望能够使用这个对话框类在XAML这样的:

<my:Dialog x:Class="MyDialogTest.TestDialog" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:my="clr-namespace:Commons;assembly=Commons" 
     Title="Outline" Height="800" Width="800"> 
    <!-- Dialog contents here --> 
</my:Dialog> 

但是,设置对话框的内容,而不是Dialog.Content何时会使用Window.Content。我如何完成这项工作?

回答

1

您可能需要在“您的”类中指定一个属性作为“内容属性”,以便您的Dialog的XAML“内容”所描述的子元素可以放入其中而不是放在“content”属性中您的基本窗口。

[ContentProperty("Content")] 
public class Dialog : Window { 

如果不工作,那么请尝试更改名称.....所以试试这个:

[ContentProperty("DialogContent")] 
public class Dialog : Window { 

public new UIElement DialogContent { 
     get { return this.m_mainContent.Child; } 
     set { this.m_mainContent.Child = value; } 
    } 
+0

正是我一直在寻找。仅供参考:第一个版本(“内容”)不起作用。我必须按照您的建议将该属性重命名为“DialogContent”。 –