Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value of x:Uid programmatically

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.

like image 212
Naresh Ravlani Avatar asked Dec 29 '16 09:12

Naresh Ravlani


3 Answers

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;
like image 140
mm8 Avatar answered Nov 13 '22 14:11

mm8


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. :)

like image 3
Jerry Nixon Avatar answered Nov 13 '22 13:11

Jerry Nixon


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
like image 1
Charlie Avatar answered Nov 13 '22 14:11

Charlie