Callum Linington
Callum Linington

Reputation: 14417

Bind to a Name property of a grid WPF

So I have my xaml:

<Grid 
       Name="{x:Static enums:DropTargetNames.ItemsGridView}" />

So the enums is the namespace, the DropTargetNames is a static class and the MasterProgramGridView is a static string. The idea being to prevent mistypes when coding, because these get used in multiple places.

Unforatunately c# WPF doesn't allow this. So is there another property I can set like this to use as an identifier for the grid?

My code identifying the grid is this:

var grid = dropInfo.Target as Grid;
var name = grid.Name;

switch (name) {

}

In the switch you use the DropTargetNames.ItemsGridView or other static strings.

Upvotes: 0

Views: 1668

Answers (2)

Callum Linington
Callum Linington

Reputation: 14417

So in the end, I went with the comment about tag. That was exactly what I needed:

<Grid Tag="{x:Static enums:DropTargetNames.ItemsGridView}">

</Grid>

C#:

var grid = dropInfo.Target as Grid;

switch (grid.Tag as string)
{

}

All good!

Upvotes: 0

dharshana jagoda
dharshana jagoda

Reputation: 430

You can try setting it indirectly through an AttachedProperty, lets say in a class called ABC

Lets say that the attached property is declared like this

    public static readonly DependencyProperty DynamicNameProperty = DependencyProperty.RegisterAttached(
        "DynamicName", typeof(object), typeof(FrameworkElement), new PropertyMetadata(default(object), PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
    {
        FrameworkElement frameworkElement = (FrameworkElement)dependencyObject;
        if (eventArgs.NewValue != null)
        {
            frameworkElement.Name = eventArgs.NewValue.ToString();
        }
    }

In XAML you could set the name like this

<Grid 
   prefix:ABC:DynamicName="{x:Static enums:DropTargetNames.ItemsGridView}" />

Upvotes: 1

Related Questions