2010-09-26 18 views
17

Digamos que tengo 2 botones en un elemento y quiero configurar los 2 elementos para que siempre llenen 1/2 ancho de su elemento contenedor cada uno, ¿puedo hacerlo?WPF: ¿Puedo establecer el ancho de un elemento por porcentajes?

ACTUALIZACIÓN

Por qué no puedo hacer algo como

<StackPanel Orientation="Horizontal" Grid.Row="0"> 
    <Button Content="Click me" Command="{Binding ClickCommand}" Width="1*" /> 
    <Button Content="Exit" Command="{Binding CloseCommand}" Width="1*" /> 
</StackPanel> 

qué doesnt el trabajo 1 * en este contexto? me sale el error

No se puede convertir "1 *"

+1

No funciona porque está utilizando un StackPanel. El tamaño de estrellas solo funciona con Grid. – ASanch

+3

oh y, en particular, el tamaño de estrellas solo se puede realizar en la propiedad ColumnDefinition.Width o en la propiedad RowDefinition.Height. No se puede configurar en los controles secundarios (como lo que hizo arriba con la propiedad Ancho del botón). – ASanch

Respuesta

43

Se puede utilizar un Grid con dos columnas para esto.

<Grid> 
    <Grid.ColumnDefinitions> 
    <ColumnDefinition Width="1*"/> 
    <ColumnDefinition Width="1*"/> 
    </Grid.ColumnDefinitions> 

    <Button Grid.Column="0">Button1</Button> 
    <Button Grid.Column="1">Button2</Button> 
</Grid> 

Aviso el uso de estrella (*) en la propiedad ColumnDefinition.Width. Esto significa que ambas columnas ocuparán la misma cantidad de espacio. Por lo tanto, en el ejemplo anterior, cada botón ocupará la mitad del espacio disponible del Grid. Por lo tanto, si hace que un Width sea igual a 2*, esa columna ocupará el doble de espacio que la otra columna. Espero que esto tenga sentido.

+0

Me olvidé de todo sobre el * thingy! gracias –

+0

oh, mira mi actualización –

1

Creé un ContentControl que me permite ajustar el contenido para agregar un porcentaje dinámico de ancho/alto.

/// <summary> 
/// This control has a dynamic/percentage width/height 
/// </summary> 
public class FluentPanel : ContentControl, IValueConverter 
{ 
    #region Dependencie Properties 

    public static readonly DependencyProperty WidthPercentageProperty = 
     DependencyProperty.Register("WidthPercentage", typeof(int), typeof(FluentPanel), new PropertyMetadata(-1, WidthPercentagePropertyChangedCallback)); 

    private static void WidthPercentagePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) 
    { 
     ((FluentPanel)dependencyObject).OnWidthPercentageChange(); 
    } 

    public int WidthPercentage 
    { 
     get { return (int)GetValue(WidthPercentageProperty); } 
     set { SetValue(WidthPercentageProperty, value); } 
    } 

    public static readonly DependencyProperty HeightPercentageProperty = 
     DependencyProperty.Register("HeightPercentage", typeof(int), typeof(FluentPanel), new PropertyMetadata(-1, HeightPercentagePropertyChangedCallback)); 

    private static void HeightPercentagePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) 
    { 
     ((FluentPanel)dependencyObject).OnHeightPercentageChanged(); 
    } 

    public int HeightPercentage 
    { 
     get { return (int)GetValue(HeightPercentageProperty); } 
     set { SetValue(HeightPercentageProperty, value); } 
    } 

    #endregion 

    #region Methods 

    private void OnWidthPercentageChange() 
    { 
     if (WidthPercentage == -1) 
     { 
      ClearValue(WidthProperty); 
     } 
     else 
     { 
      SetBinding(WidthProperty, new Binding("ActualWidth") { Source = Parent, Converter = this, ConverterParameter = true }); 
     } 
    } 

    private void OnHeightPercentageChanged() 
    { 
     if (HeightPercentage == -1) 
     { 
      ClearValue(HeightProperty); 
     } 
     else 
     { 
      SetBinding(HeightProperty, new Binding("ActualHeight") { Source = Parent, Converter = this, ConverterParameter = false }); 
     } 
    } 

    #endregion 

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if ((bool)parameter) 
     { 
      // width 
      return (double)value * (WidthPercentage * .01); 
     } 
     else 
     { 
      // height 
      return (double)value * (HeightPercentage * .01); 
     } 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 
Cuestiones relacionadas