2009-06-09 88 views
6

我找到了這個問題的ASP,但它並沒有幫助我很多......可以包含其他控件(使用時)C#用戶控制

我希望做的是以下:我想創建一個具有集合作爲屬性的集合的用戶控件,以及用於導航該集合的按鈕。我希望能夠將此用戶控件綁定到集合並在其上顯示不同的控件(包含來自該集合的數據)。 就像你在一個形式下緣的MS Access有什麼...

更精確:

當我實際使用我的應用程序的控制(後我創造了它),我想能夠在<myControly></mycontrol>之間添加多個控件(文本框,標籤等) 如果我現在這樣做了,那麼我的用戶控件上的控件就會消失。

+2

接受的答案什麼問題呢?這聽起來很容易...... – Tony 2009-06-09 12:39:23

+0

問題不在於收集和導航按鈕,而在於我希望在另一個應用程序中使用它時,可以將控件添加到用戶控件中。 – 2009-06-09 12:52:28

+0

如果我嘗試在和之間放置多個控件,那麼我只能在其中放置一個控件。如果我嘗試一個網格,我的自定義控件上的控件就會消失。 – 2009-06-09 13:20:05

回答

8

這裏是做你想要什麼的一種方式的示例:

首先,代碼 - UserControl1.xaml.cs

public partial class UserControl1 : UserControl 
{ 
    public static readonly DependencyProperty MyContentProperty = 
     DependencyProperty.Register("MyContent", typeof(object), typeof(UserControl1)); 


    public UserControl1() 
    { 
     InitializeComponent(); 
    } 

    public object MyContent 
    { 
     get { return GetValue(MyContentProperty); } 
     set { SetValue(MyContentProperty, value); } 
    } 
} 

而且用戶控件的XAML - UserControl1.xaml

<UserControl x:Class="InCtrl.UserControl1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="300" Width="300" Name="MyCtrl"> 
    <StackPanel> 
     <Button Content="Up"/> 
     <ContentPresenter Content="{Binding ElementName=MyCtrl, Path=MyContent}"/> 
     <Button Content="Down"/> 
    </StackPanel> 
</UserControl> 

最後,XAML使用我們美好的新控制:

<Window x:Class="InCtrl.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:me="clr-namespace:InCtrl" 
    Title="Window1" Height="300" Width="300"> 
    <Grid> 
     <me:UserControl1> 
      <me:UserControl1.MyContent> 
       <Button Content="Middle"/> 
      </me:UserControl1.MyContent> 
     </me:UserControl1> 
    </Grid> 
</Window> 
0

UserControl可能不是實現此目的的最佳方法。你想在內容上添加裝飾,這基本上是Border所做的:它有一個子元素,並在邊緣添加自己的東西。

查看Decorator類,Border是從哪裏下來的。如果你製作自己的邊境後裔,你應該很容易做到你想要的。不過,我相信這需要編寫代碼,而不是XAML。

您可能仍然想要使用UserControl來將按鈕封裝在底部,這樣您就可以將可視化設計器用於部分流程。但裝飾者將是將各個部分粘合在一起並允許用戶定義的內容的好方法。

0

這裏有一個link到內置的控制(HeaderedContentControl),做同樣的事情,不同之處在於它是在WPF現有的控制,因爲NET 3.0

相關問題