开发者

WPF Putting a Button on a Label

开发者 https://www.devze.com 2022-12-09 04:20 出处:网络
I\'ve got a listbox of Labels, each bound to a LabelName and LabelColor. I want to add a small button that resembles an \"X\" and attach it on the right side of the Label. I want it to look seamless,

I've got a listbox of Labels, each bound to a LabelName and LabelColor. I want to add a small button that resembles an "X" and attach it on the right side of the Label. I want it to look seamless, like the X is very non-intrusive. Any ideas how to do this? The stuff between the <Label.ContentTemplate> does 开发者_开发技巧NOT work. I don't even want it to looks like a clickable button, just an "X" that you can click on that fires off a button-click event.

<DataTemplate x:Key="LabelsListDataTemplate">
        <Border>
            <StackPanel Orientation="Horizontal">
                <Label Margin ="3,5,3,5" BorderThickness="1" BorderBrush="Black" 
                           Background="{Binding Path=DefaultColor}"
                           Content="{Binding Path=LabelName}">
                    <Label.ContentTemplate>
                        <DataTemplate>
                            <Button Background="{Binding Path=DefaultColor}" Content="X" />
                        </DataTemplate>
                    </Label.ContentTemplate>
                </Label>
            </StackPanel>
        </Border>
    </DataTemplate>


Why do you want to add button to the controltemplate. Check the below code works or not.

<DataTemplate x:Key="LabelsListDataTemplate">
    <Border>
        <StackPanel Orientation="Horizontal">
            <Label Margin ="3,5,3,5" BorderThickness="1" BorderBrush="Black" 
                       Background="{Binding Path=DefaultColor}"
                       Content="{Binding Path=LabelName}"/>
              <Button Background="{Binding Path=DefaultColor}" Content="X" />               
        </StackPanel>
    </Border>
</DataTemplate>


Excellent, that worked well. I tweaked it just a little bit to get the "X" button to appear a little more flush and natural looking with the Label itself, as follows:

<DataTemplate x:Key="LabelsListDataTemplate">
    <Border>
        <StackPanel Orientation="Horizontal">
            <Label Margin ="3,5,0,5" BorderThickness="1" BorderBrush="Black" Name="RowLabel" 
                       Background="{Binding Path=DefaultColor}"
                       Content="{Binding Path=LabelName}"></Label>
            <Button Background="{Binding Path=DefaultColor}" Content="X" Height="{Binding ElementName=RowLabel, Path=ActualHeight}"
                    Margin="0,5,3,5" />
        </StackPanel>
    </Border>
</DataTemplate>

I basically set the height of the button to the height of the Label. Then I did some margin-fudging to get them to appear right next to one-another. Thanks for the help!

0

精彩评论

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

关注公众号