2009-05-18 13 views
42

tengo los dos botones siguientes en XAML:¿Cómo puedo definir una variable en XAML?

<Button Content="Previous" 
     Margin="10,0,0,10"/> 
<Button Content="Next" 
     Margin="0,0,10,10"/> 

¿Cómo puedo definir "10" a ser una variable para que pueda cambiarlo en un solo lugar, algo como esto:

PSEUDO CÓDIGO:

<variable x:key="theMargin"/> 
<Button Content="Previous" 
     Margin="{Variable theMargin},0,0,{Variable theMargin}"/> 
<Button Content="Next" 
     Margin="0,0,{Variable theMargin},{Variable theMargin}"/> 

Respuesta

72

Prueba esto:

añadir a la cabeza de la xamlfile

xmlns:System="clr-namespace:System;assembly=mscorlib" 

a continuación, añadir esta al recurso sección:

<System:Double x:Key="theMargin">2.35</System:Double> 

Por último, utilice un espesor en el margen:

<Button Content="Next"> 
    <Button.Margin> 
     <Thickness Top="{StaticResource theMargin}" Left="0" Right="0" 
        Bottom ="{StaticResource theMargin}" /> 
    </Button.Margin> 
</Button> 

Una gran cantidad de tipos de sistemas puede definirse así: int, char, string, DateTime, etc

Nota: Usted es bien ... Tenía que hacer algo mejor prueba .. cambiado de código para que se debe trabajar

+0

hmmm, añado 2.35 en Window.Resources y obtuve "System: Double was not found", agregué "System" como referencia pero no lo hice t ayuda, ¿qué me estoy perdiendo? –

+0

El doble no aparece en el menú desplegable, solo p. "RegistryHive" y otros tres, tengo referencias de System.Core, ¿a qué más debo hacer referencia? –

+1

Encontré mi problema: estaba agregando este xmlns: System = "clr-namespace: Microsoft.Win32; assembly = mscorlib" y debería haber estado agregando esto: xmlns: System = "clr-namespace: System; assembly = mscorlib" –

0

declararemos como (sólo lectura posibl estática o const) campo en el archivo de código subyacente.

1

¿Por qué no intentas agregar el valor como StaticResource?

Resources.Add("theMargin", 10); 

entonces se puede obtener ese valor como esto:

<Button Content="Previous" 
     Margin="{StaticResource theMargin},0,0,{StaticResource theMargin}"/> 
<Button Content="Next" 
     Margin="0,0,{StaticResource theMargin},{StaticResource theMargin}"/> 
+0

añadí Resources.Add (" theMargin ", 50); después de InitializeComponent en mi código, pero XAML no pudo acceder a él. –

1

es necesario invocar esto antes InitializeComponent o utilizar INotifyPropertyChanged interfaz después de que

1

Imagen similar a la respuesta de Sorskoot, se puede agregar un recurso de espesor de usar, definiendo de este modo cada dirección margen independientemente

<UserControl.Resources> 
    <Thickness x:Key="myMargin" Top="5" Left="10" Right="10" Bottom ="5"></Thickness> 
</UserControl.Resources> 

Entonces sólo tiene que utilizar el espesor como el margen:

<Button Content="Next" Margin="{StaticResource myMargin}"/> 
Cuestiones relacionadas