私はExpression Blendを使用してボタンをデザインしていました。新しいボタンを作成し、その中のすべてを削除してボタンのテンプレートを編集しました。次に、グリッドを追加して「グリッド」という名前を付けました。グリッドの中で私はテキストブロックを追加し、それを "textBlock"と呼んだ。次に、アプリケーションの下にテンプレートを保存しました。実行時にWPFボタンを編集するには
これはapp.xamlファイルのコンテンツです。
<Style x:Key="CustomButtonStyle" TargetType="{x:Type Button}">
<Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
<Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
<Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid x:Name="grid" HorizontalAlignment="Left" Height="40" VerticalAlignment="Top" Width="90">
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Margin="5,5,0,0" Height="25" Width="75" FontSize="17.333"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsDefaulted" Value="true"/>
<Trigger Property="IsMouseOver" Value="true"/>
<Trigger Property="IsPressed" Value="true"/>
<Trigger Property="IsEnabled" Value="false"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
は基本的に私は何をしようとしていますことは、実行時にボタンを作成ボタンにこのスタイルを適用すると、ボタンのテンプレートに行く、とのテンプレートにテキストブロックのテキストプロパティを変更することですボタン。
まず、実行時にボタンを作成するのではなく、コンパイル時にボタンを作成して「customButton」という名前を付けました。次に、ボタンのテンプレートのテキストブロックのテキストプロパティを編集しようとしましたが、例外が発生しました。
TextBlock tb = this.customButton.Template.FindName("textBlock", customButton) as TextBlock;
tb.Text = "ASDDDQWEQWEQWE";
ありがとうございました!
ユーザがテンプレートを簡単に変更する必要がある場合、それを逆アセンブルしなければならないテンプレートデフォルトのボタンテンプレートは 'ContentPresenter'を使って任意のContentを表示します(これはテキストではありません!!)。私は同じことをお勧めします – ASh
実行時にテキストボックスの内容を動的に変更したい場合は、 'Text'フィールドをプロパティにバインドし、コード内のプロパティを変更することを検討してください。 – Jack
会社名、画像、株価上昇率などの会社の株価情報を1つのボタンで表すためのボタンを作成したいと考えています。したがって、実行時には、外部APIから上位10個の在庫を取得し、実行時に情報とともに10個のボタンを作成し、それをメインウィンドウのスタックパネルに追加します。 –