以编程方式设置x:Uid的值

时间:2016-12-29 09:04:07

标签: c# xaml uwp winrt-xaml windows-mobile

我在XAML视图的代码隐藏文件中创建一个AppBarButton。 目前,我在XAML中定义了AppBarButton,如下所示:

<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" />    

我想将此XAML转换为C#代码。以下是我到目前为止的代码。

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);

我唯一想要的是将x:Uid =“AppBar_TransferVisit”转换为等效的C#代码。对此的任何帮助都非常感谢。

谢谢, Naresh Ravlani。

3 个答案:

答案 0 :(得分:5)

您似乎无法在UWP中以编程方式实际设置x:Uid属性:

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

这是因为它是XAML指令而不是属性:

Doing localization in visualstatemanager by changing x:uid?

您必须直接设置AppBarButton的相应属性,例如:

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

答案 1 :(得分:3)

我可以确认我已经与UWP-XAML平台团队谈过以编程方式访问x:UID,这是不可能的。如果你问我,这是一个缺点。但它正是在这个时候。 :)

答案 2 :(得分:1)

有一种解决方法,使用XamlReader从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
相关问题