2010-10-19 30 views
8

Nếu tôi gán một đoạn văn bản cho thuộc tính Content của ContentPresenter, điều khiển TextBlock được tạo bởi ContentPresenter tại thời gian hiển thị để chứa văn bản đó.WPF 4 ContentPresenter TextWrapping style không được áp dụng cho TextBlock

Nếu tôi tạo kiểu áp dụng cho TextBlock thuộc tính và chỉ định kiểu đó cho số ContentPresenter, thì dường như không áp dụng cho TextBlock s được tạo ngầm.

<Style x:Key="SampleStyle"> 
    <Setter Property="TextBlock.TextWrapping" Value="Wrap"/> 
</Style> 

<ContentPresenter Content="This is a Test piece of text." Style="{StaticResource SampleStyle}"/> 

Có cách nào để áp dụng phong cách này thành công đến autogenerated TextBlock s ngắn của việc áp dụng nó cho tất cả TextBlock s (ví dụ khai báo kiểu như TargetType="TextBlock" không có Key)?

Trả lời

32

Bạn có thể làm điều này ...

<Window.Resources> 
    <ResourceDictionary> 
     <Style TargetType="{x:Type TextBlock}" x:Key="WrappingStyle"> 
      <Setter Property="TextWrapping" Value="Wrap"/> 
     </Style> 
    </ResourceDictionary> 
</Window.Resources> 

... sau đó nơi bạn xác định bạn ContentPresenter ...

<ContentPresenter Content="This text is going to wrap..."> 
      <ContentPresenter.Resources> 
       <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource WrappingStyle}"/> 
      </ContentPresenter.Resources> 
</ContentPresenter> 

Các TargetType được thiết lập kể từ khi bạn biết ContentPresenter sẽ không phải lúc nào giữ TextBlock trong đó.

+0

Cảm ơn bạn rất MCH – Sayka

5

Nếu bạn không sử dụng các phong cách khác, bạn có thể áp dụng nó trực tiếp đến người dẫn chương trình nội dung:

<ContentPresenter.Resources> 
    <Style TargetType="{x:Type TextBlock}"> 
     <Setter Property="TextWrapping" Value="Wrap"/> 
    </Style> 
</ContentPresenter.Resources> 
Các vấn đề liên quan