Wpf 引用在xaml中定义的值
我有几个控件,我希望它们共享相同的宽度,在编译时指定。所以要么它们都使用10的宽度,要么它们都使用20的宽度,以此类推 什么是正确的方法来定义这个值一次,然后像变量一样使用它呢 “给你想法”伪代码:Wpf 引用在xaml中定义的值,wpf,xaml,Wpf,Xaml,我有几个控件,我希望它们共享相同的宽度,在编译时指定。所以要么它们都使用10的宽度,要么它们都使用20的宽度,以此类推 什么是正确的方法来定义这个值一次,然后像变量一样使用它呢 “给你想法”伪代码: double my_width = 10; <Label width=my_width content="some text"/> <Label width=my_width content="some text"/> <Label width=my_width con
double my_width = 10;
<Label width=my_width content="some text"/>
<Label width=my_width content="some text"/>
<Label width=my_width content="some text"/>
<Label width=my_width content="some text"/>
双倍my_宽度=10;
最简单的方法是在窗口
的加载
事件中,放入此代码:
this.DataContext = my_width;
并将标记更改为:
<Label width="{Binding}" content="some text"/>
并将其用作
<Label Width="{x:Static local:Window1.LabelWidth}" Content="Some Text" />
在窗口类中或放置此标签的任何位置
--
另一件简单的事情是创建样式:
<Window.Resources>
<Style x:Key="LabelStyle">
<Setter Property="Width" Value="100" />
</Style>
</Window.Resources>
然后像这样使用它:
<Label Style="{StaticResource LabelStyle}" Content="Some Text" />
我看到了一个不错的小把戏
<UserControl.Resources> // or wherever it's handy to stick the resource
<GridLength x:Key="NormalWidth">50</GridLength>
</UserControl.Resources>
干杯,贝里尔
<Label Style="{StaticResource LabelStyle}" Content="Some Text" />
<UserControl.Resources> // or wherever it's handy to stick the resource
<GridLength x:Key="NormalWidth">50</GridLength>
</UserControl.Resources>
Label Width="{StaticResource NormalWidth}"