UWP: How to avoid style name (x: Name) in Templete Control development?
With UWP (or WPF), I add x: Name to my XAML style. and the style doesn't work at all with x: name. Why?
Now I am developing a Template control. To change the style property with "SetValue" I have to add a name to my style. then I added the name x: Name = "MyStyleName", but this creates a problem.
Here's a simple x: Name style code example.
<Grid Background="Black" Width="200" Height="200" >
<Grid.Resources>
<Style x:Name="MyStyleName" TargetType="Ellipse">
<Setter Property="Height" Value="100" />
<Setter Property="Width" Value="100" />
<Setter Property="Stroke" Value="Red"/>
</Style>
</Grid.Resources>
<Ellipse x:Name="Circle1" />
<Ellipse x:Name="Circle2" />
</Grid>
The main reason I am adding x is: Title by style. During the design of the template control, I want to access STYLE by name.
var _grid = this.GetTemplateChild(GRID_NAME) as Grid;
if (_grid != null)
{
// change grid margin.
_grid.Margin = new Thickness(0, 5, 0, 0);
// get Style of Grid
var _gridStyle = _grid .Resources[GRID_STYLE_NAME] as Style;
if(_gridStyle != null)
{
// Change Gird Height as STYLE !
_gridStyle.SetValue(FrameworkElement.HeightProperty, 10);
}
}
Is there a good way to avoid Style x: Name
source to share
Instead of resources, you need to use x:Key
. Basically it is the ID inside ResourceDictionary
.
But can we improve this? Since I don't recommend such a hard line. What if the developer using your control doesn't know they need to specify this style?
The solution to this is to create a GridStyle
type dependency property Style
in your control and bind it to an existing style in your XAML file (for example, yours Generic.xaml
inside the Themes folder, where you put the default style for your control). This way, other developers are free to apply their own style Grid
.
source to share