开发者

How do I properly style a button in WPF?

I know this is a basic question, but I'm having a bit of trouble understanding how to do this properly.

Given the following XAML:

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

        <Image Grid.Column="0" Width="16" Height="16" Source="Resources/accept.png" />
        <TextBlock Grid.Column="1" Margin="2">Continue</TextBlock>
    </Grid>
</Button>

How would I convert that to a style so that it can be easily reused? What if I were to want to supply the image source and text in an attribute? Is that possible?

On a开发者_运维问答 related note, what are the best practices for structuring the files where you store your styles, etc? Do you just drop them into a new XAML file and stick them in a styles solution folder?

I'm very new to WPF, so, again, I apologize for the basic question.

Ian


Edit 1:

There are a couple of ways to style controls. You can access them as a StaticResource, or supply a TargetType so all the styles get applied to the Controls of that type.

To parameterize your style you could consider DataBinding. If for instance you have a model that supplies content for these buttons you could try something like:

<Grid.Resources>
    <Style TargetType="Button">
        <Setter Property="Content">
            <Setter.Value>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="16" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <Image Grid.Column="0" Width="16" Height="16" Source="{Binding Path=Image}" />
                    <TextBlock Grid.Column="1" Margin="2" Text="{Binding Path=Text}" />
                </Grid>
            </Setter.Value>
        </Setter>
    </Style>
</Grid.Resources>

<Button x:Name="myButton1"  Width="100" Height="100" />

This would be an example of how to set the content.

myButton1.DataContext = new ButtonCaption {Text = "Testing"};

public class ButtonCaption
{
    public Image Image { get; set; }
    public string Text { get; set; }
}


what you really want is a control template, not just a simple style. Here is a pretty decent tutorial on the whole thing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜