wpf 如何在 XAML 中定义变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/877304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I define a variable in XAML?
提问by Edward Tanguay
I have the following two buttons in XAML:
我在 XAML 中有以下两个按钮:
<Button Content="Previous"
Margin="10,0,0,10"/>
<Button Content="Next"
Margin="0,0,10,10"/>
How can I define "10" to be a variable so I can change it in one place, something like this:
如何将“10”定义为变量,以便我可以在一个地方更改它,如下所示:
PSEUDO CODE:
伪代码:
<variable x:key="theMargin"/>
<Button Content="Previous"
Margin="{Variable theMargin},0,0,{Variable theMargin}"/>
<Button Content="Next"
Margin="0,0,{Variable theMargin},{Variable theMargin}"/>
回答by Sorskoot
Try this:
尝试这个:
add to the head of the xamlfile
添加到 xamlfile 的头部
xmlns:System="clr-namespace:System;assembly=mscorlib"
Then Add this to the resource section:
然后将其添加到资源部分:
<System:Double x:Key="theMargin">2.35</System:Double>
Lastly, use a thickness on the margin:
最后,在边距上使用厚度:
<Button Content="Next">
<Button.Margin>
<Thickness Top="{StaticResource theMargin}" Left="0" Right="0"
Bottom ="{StaticResource theMargin}" />
</Button.Margin>
</Button>
A lot of system types can be defined this way: int, char, string, DateTime, etc
很多系统类型都可以这样定义:int、char、string、DateTime等
Note: You're right... Had to do some better testing.. changed to code so that it should work
注意:你是对的......不得不做一些更好的测试......更改为代码以便它应该工作
回答by CodyF
Similiar to Sorskoot's answer, you can add a thickness resource to use, thereby defining each margin direction independently
类似于 Sorskoot 的回答,您可以添加要使用的厚度资源,从而独立定义每个边距方向
<UserControl.Resources>
<Thickness x:Key="myMargin" Top="5" Left="10" Right="10" Bottom ="5"></Thickness>
</UserControl.Resources>
Then just use the Thickness as the Margin:
然后只需使用厚度作为边距:
<Button Content="Next" Margin="{StaticResource myMargin}"/>
回答by Andrew Hare
Why don't you try adding the value as a StaticResource
?
为什么不尝试将值添加为 a StaticResource
?
Resources.Add("theMargin", 10);
Then you can get that value like this:
然后你可以得到这样的值:
<Button Content="Previous"
Margin="{StaticResource theMargin},0,0,{StaticResource theMargin}"/>
<Button Content="Next"
Margin="0,0,{StaticResource theMargin},{StaticResource theMargin}"/>
回答by inkubpl
You need invoke this before InitializeComponent or use INotifyPropertyChanged Interface after that
您需要在 InitializeComponent 之前调用它或之后使用 INotifyPropertyChanged 接口
回答by mihails.kuzmins
In .NET Core @Sorskoot's answer was working, but produced a warning. So instead I used this namespace declaration:
在 .NET Core 中,@Sorskoot 的回答有效,但产生了警告。所以我使用了这个命名空间声明:
xmlns:system="clr-namespace:System;assembly=System.Runtime"