2012-12-27 36 views
0

我想製作一個UserControl,我可以在我的應用程序中使用各種按鈕。有沒有辦法通過XAML將參數傳遞給UserControls?我的應用程序中的大多數按鈕都由兩個矩形(一個在另一箇中)和一些用戶指定的顏色組成。它也可能有一個圖像。我想它的行爲是這樣的:XAML中的自定義用戶控件(按鈕),帶參數

<Controls:MyCustomButton MyVarColor1="<hard coded color here>" MyVarIconUrl="<null if no icon or otherwise some URI>" MyVarIconX="<x coordinate of icon within button>" etc etc> 

然後我想能夠使用這些值的XAML內側(IconUrl分配到圖標的來源,等等,等等按鈕內。

我只是在想這個錯誤的方式或者是有辦法做到這一點?我的目的是有較少的XAML代碼爲我的所有按鈕。

謝謝!

回答

5

是的,你可以在XAML訪問一個Control任何財產,但如果你在UserControl要進行數據綁定,動畫等特性必須DependencyProperties

例如:

public class MyCustomButton : UserControl 
{ 
    public MyCustomButton() 
    { 
    } 

    public Brush MyVarColor1 
    { 
     get { return (Brush)GetValue(MyVarColor1Property); } 
     set { SetValue(MyVarColor1Property, value); } 
    } 

    // Using a DependencyProperty as the backing store for MyVarColor1. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty MyVarColor1Property = 
     DependencyProperty.Register("MyVarColor1", typeof(Brush), typeof(MyCustomButton), new UIPropertyMetadata(null)); 



    public double MyVarIconX 
    { 
     get { return (double)GetValue(MyVarIconXProperty); } 
     set { SetValue(MyVarIconXProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for MyVarIconX. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty MyVarIconXProperty = 
     DependencyProperty.Register("MyVarIconX", typeof(double), typeof(MyCustomButton), new UIPropertyMetadata(0)); 



    public Uri MyVarIconUrl 
    { 
     get { return (Uri)GetValue(MyVarIconUrlProperty); } 
     set { SetValue(MyVarIconUrlProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for MyVarIconUrl. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty MyVarIconUrlProperty = 
     DependencyProperty.Register("MyVarIconUrl", typeof(Uri), typeof(MyCustomButton), new UIPropertyMetadata(null)); 

} 

XAML:

<Controls:MyCustomButton MyVarColor1="AliceBlue" MyVarIconUrl="myImageUrl" MyVarIconX="60" /> 
+0

我這樣做,正如你建議我可以設置對用戶控件屬性。我如何從usercontrol內部訪問它? –

+0

一些搜索後,我發現「{Binding Path = MyVarColor1}」工作...感謝您的幫助! –