Set value of x:Uid programmatically

3.1k views Asked by At

I am creating an AppBarButton in code behind file of XAML view. Currently, I have AppBarButton defined in XAML as below:

<AppBarButton x:Name="SelectVisitAppBarButton" x:Uid="AppBar_TransferVisit"  Margin="0,0,12,0" Icon="Bullets" Style="{StaticResource TransferAppBarButtonStyle}" IsEnabled="{Binding ScheduleViewVm.IsVisitSelectionEnable}" Click="SelectVisit_Click" />    

I want to convert this XAML into C# code. Following is the code that I have till now.

AppBarButton SelectVisitAppBarButton = new AppBarButton();    
SelectVisitAppBarButton.Margin = new Thickness(0, 0, 12, 0);
SymbolIcon bulletSymbol = new SymbolIcon();
bulletSymbol.Symbol = Symbol.Bullets;
SelectVisitAppBarButton.Icon = bulletSymbol;
SelectVisitAppBarButton.Style = App.Current.Resources["TransferAppBarButtonStyle"] as Style;
SelectVisitAppBarButton.Click += SelectVisit_Click;
Binding b = new Binding();
b.Source = _viewModel.ScheduleViewVm.IsVisitSelectionEnable;
SelectVisitAppBarButton.SetBinding(Control.IsEnabledProperty, b);
Appbar.Children.Add(SelectVisitAppBarButton);

The only thing I am looking for is to convert x:Uid="AppBar_TransferVisit" into its equivalent C# code. Any help on this is highly appreciated.

Thanks, Naresh Ravlani.

3

There are 3 answers

0
mm8 On

It seems that you cannot actually set the x:Uid attribute programmatically in UWP:

How to set control x:Uid attribute programmatically for a metro app control?

This is because it's a XAML directive rather than a property:

Doing localization in visualstatemanager by changing x:uid?

You will have to set the corresponding properties of the AppBarButton directly, e.g.:

AppBarButton SelectVisitAppBarButton = new AppBarButton();
var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
var text = resourceLoader.GetString("SomeResource");
AppBarButton SelectVisitAppBarButton = new AppBarButton();
SelectVisitAppBarButton.Content = text;
0
Charlie On

There's a workaround, using XamlReader to load the button from xaml.

 Button btn = (Button)XamlReader.Load("<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Uid='btnSubmit' Margin='5,0,0,0'/>");
 btn.OtherProperty = xxxx
1
Jerry Nixon On

I can confirm that I have spoken to the UWP-XAML platform team about programatically accessing x:UID and it is not possible. This is a shortcoming, if you ask me. But it is what it is at this time. :)