How can I define a variable in XAML?

后端 未结 5 824
灰色年华
灰色年华 2020-11-30 02:32

I have the following two buttons in XAML:

相关标签:
5条回答
  • 2020-11-30 02:41

    In .NET Core @Sorskoot's answer was working, but produced a warning. So instead I used this namespace declaration:

    xmlns:system="clr-namespace:System;assembly=System.Runtime"
    
    0 讨论(0)
  • 2020-11-30 02:47

    Try this:

    add to the head of the 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

    Note: You're right... Had to do some better testing.. changed to code so that it should work

    0 讨论(0)
  • 2020-11-30 02:48

    Why don't you try adding the value as 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}"/>
    
    0 讨论(0)
  • You need invoke this before InitializeComponent or use INotifyPropertyChanged Interface after that

    0 讨论(0)
  • 2020-11-30 03:02

    Similiar to Sorskoot's answer, you can add a thickness resource to use, thereby defining each margin direction independently

    <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}"/>
    
    0 讨论(0)
提交回复
热议问题