Set value of x:Uid programmatically
Asked Answered
S

3

5

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.

Strage answered 29/12, 2016 at 9:4 Comment(0)
W
5

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;
Wilinski answered 29/12, 2016 at 10:50 Comment(0)
C
3

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

Crispen answered 22/1, 2017 at 22:51 Comment(1)
It will be helpful if you can share any document link where I can find this.Strage
C
1

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
Chinquapin answered 14/9, 2017 at 4:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.