Create a control in Resources and reuse it in XAML WPF

后端 未结 3 1495
遥遥无期
遥遥无期 2020-12-14 07:34

I just try to create a simple Symbol/Geometry/Control and change and reuse it in several places in the same window.

Example: a black square with a circle in the midd

3条回答
  •  情书的邮戳
    2020-12-14 07:53

    When you define a arbitrary Control in Resources, you can use it in the future in Control which have property Content and derived from Control class. These are the followings: ContentControl, Label, ContentPresenter, etc.

    Also you must set x:Shared="False" for resource if you want to use this resource in many Controls, because x:Shared="True" by default then one Resource is common to all - in this case, the system swears on the duplicate Content. When x:Shared="False" when is created Resource for each element whenever it its request. Quote from MSDN:

    When set to false, modifies WPF resource-retrieval behavior so that requests for the attributed resource create a new instance for each request instead of sharing the same instance for all requests.

    Example:

    
        
            
            
        
    
    
    
                
        
    

    To change the Fill of Ellipse in code-behind, you can like this:

    private void ChangeBackground_Click(object sender, RoutedEventArgs e)
    {
        var canvas = MyContentControl.Content as Canvas;
    
        if (canvas != null)
        {
            foreach (var item in canvas.Children)
            {
                if (item is Ellipse)
                {
                    ((Ellipse)item).Fill = Brushes.Green;
                }
            }
        }
    }
    

提交回复
热议问题