簡體   English   中英

結合使用XAML和自定義控件

[英]Using XAML with custom control

我有一個從Control和一些Path XAML源代碼派生的自定義WPF控件:

<Path Width="16" Height="16" Margin="6,0,0,0" x:Key="CheckMark" SnapsToDevicePixels="False" Stroke="Black" Fill="Black" StrokeThickness="1"
     Data="M 12.4227,0.00012207C 12.4867,0.126587 12.5333,0.274536 
      12.6787,0.321411C 9.49199,3.24792 6.704,6.57336 
      4.69865,10.6827C 4.04399,11.08 3.47066,11.5573 2.83199,
      11.9706C 2.09467,10.2198 1.692,8.13196 3.8147e-006,
      7.33606C 0.500004,6.79871 1.31733,6.05994 1.93067,6.2428C 
      2.85999,6.51868 3.14,7.9054 3.60399,8.81604C 5.80133,
      5.5387 8.53734,2.19202 12.4227,0.00012207 Z " />

應該在控件的OnRender中使用該Path來繪制一些復選標記。

問題是我應該把這個XAML路徑放在哪里? 我的自定義控件沒有自己的XAML文件,但具有在Generic.xaml中聲明的默認樣式

<Style TargetType="{x:Type layers:TargetsGrid}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type layers:TargetsGrid}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

顯然,我可以將Path類型的依賴項屬性添加到控件中,並以默認樣式進行分配,但是有沒有更簡單的方法? 可能我應該將Path放置到一些單獨的XAML文件中?

為什么不把它放在邊界內?

    <ControlTemplate TargetType="{x:Type layers:TargetsGrid}">
        <Border Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}">

            <Path ... />

        </Border>
    </ControlTemplate>

您可以創建一個單獨的ResourceDictionary並將其放在其中,然后執行以下操作:

//Pseudo code, not tested
var resourcs = new ResourceDictionary(new Uri("path to your ResourceDictionary"))
var path = (Path)resources["MyPath"];

或者,如果您不打算重復使用它,則可以完全在代碼中創建Path。

或者,您可以將其與ControlTemplate一起保存在Generic.xaml中,這樣做的確沒有什么問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM