开发者

How can I replicate 'float: right' in XAML?

I want to create a ListBoxItem with a layout that includes two areas, one 'float: left' and one 'float: right', with the item overall filling the entire width allocated to the ListBox and the ListBox filling its conta开发者_如何学编程iner (ie. expanding to fill the available space).

How can I achieve this in XAML?

thanks


For the "item overall filling the entire width allocated to the ListBox" you need a style like this:

<Style TargetType="ListBoxItem">
    <Setter Property="HorizontalAlignment" Value="Stretch" />
    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>

and optionally disable horizontal scrolling for the listbox:

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" .. >

for the DataTemplate's root panel you can either use a dockpanel:

<DockPanel>
  <SomeControlLeft DockPanel.Dock="Left" Margin="0 0 5 0" />
  <SomeControlRight DockPanel.Dock="Right" Margin="5 0 0 0" />
  <SomeControlFill />
</DockPanel>

or a grid:

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="5" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="5" />
    <ColumnDefinition Width="Auto" />
  </Grid.ColumnDefinitions>

  <SomeControlLeft Grid.Column="0" />
  <SomeControlRight Grid.Column="4" />
  <SomeControlFill Grid.Column="2" />
</Grid>


This is the way I would do it:

    <Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Grid Background="Red">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <TextBlock Text="{TemplateBinding Content}"/>
                        <TextBlock Text="{TemplateBinding Tag}" Grid.Column="1"/>

                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White">

    <ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle}">
        <ListBoxItem Content="Lorem" Tag="Ipsum"/>
        <ListBoxItem Content="Hello" Tag="World"/>
        <ListBoxItem Content="Be" Tag="Happy"/>
    </ListBox>

</Grid>


Use a Grid to position or dock elements to various parts of the form/panel.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜