简体   繁体   English

ContentTemplate在Windows Phone中使用C#而不是XAML

[英]ContentTemplate using C# instead of XAML in Windows Phone

What I am trying to do is use C# to write the code of ContentTemplate instead of XAML. 我想要做的是使用C#编写ContentTemplate而不是XAML的代码。 Here is the XAML code that I have: 这是我的XAML代码:

<phone:PhoneApplicationPage.Resources>
        <DataTemplate x:Key="AnyButton">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="140"/>
                    <ColumnDefinition Width="310"/>
                </Grid.ColumnDefinitions>
                <Image Grid.Column="0" Source="/Images/AnyImage.png" Height="80" Width="80" HorizontalAlignment="Left" Margin="15,0,0,0"/>
                <TextBlock Grid.Column="1" TextWrapping="Wrap" VerticalAlignment="Center" HorizontalAlignment="Left" Text="AnyText" FontSize="30" FontFamily="{StaticResource PhoneFontFamilySemiLight}" Margin="0,0,0,0"/>
            </Grid>
        </DataTemplate>
</phone:PhoneApplicationPage.Resources>

And here is the code that I used inside my ContentPanel to use the ContentTemplate: 这是我在ContentPanel中使用的代码,用于使用ContentTemplate:

<Button x:Name="MyButton" 
        Click="MyButton_Click" 
        ContentTemplate="{StaticResource AnyButton}" 
        Width="492" Height="130" 
        Margin="6,0,6,-6" 
        Background="#003d0a"/>

Now, my question is, is it possible to write the whole code using C#? 现在,我的问题是,是否可以使用C#编写整个代码?

if you are trying to do it in styling purpose do it in the following way: 如果您尝试在样式目的中执行此操作,请按以下方式执行此操作:

<Style x:Key="MyButton" TargetType="Button">
            <Setter Property="Width" Value="460"></Setter>
            <Setter Property="Background" Value="/Images/AnyImage.png"></Setter>
        </Style>

define this in app.xaml or PhoneApplicationPage.resources and in your button control in xaml set your style to MyButton. 在app.xaml或PhoneApplicationPage.resources中定义它,并在xaml中的按钮控件中将您的样式设置为MyButton。 for example: 例如:

<Button style={StaticResource MyButton}/>

if you also want to define width and height for your image you can do it same way by defining style in value section set the value with that style. 如果您还想为图像定义宽度和高度,您可以通过在值部分中定义样式来设置具有该样式的值。 for example: 例如:

<style x:key ="MyImage" TargetType="Image">
  <setter property="Width" Value="150"/>
</style>

in my button style define background value ={StaticResource MyImage} 在我的按钮样式中定义背景值= {StaticResource MyImage}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM