简体   繁体   中英

Using XAML with custom control

I have a custom WPF control derived from Control and some Path XAML source code:

<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 " />

that Path should be used in control's OnRender to draw some check mark.

The question is where should I put this XAML Path? My custom control does not have its own XAML file, but it has default style declared in 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>

Obviously, I can add a dependency property of type Path to the control and assign it in default style, but is there some easier way? Probably I should place my Path to some separate XAML file?

Why not put it within the border?

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

            <Path ... />

        </Border>
    </ControlTemplate>

You can create a separate ResourceDictionary and place your Path in that, and do something like:

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

Or you can create your Path entirely in code if you don't plan to reuse it.

Or you can keep it in Generic.xaml alongside the ControlTemplate, I don't really see an issue in doing that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM