2012-10-02 35 views
1

我有一個UserControl,它僅包含DataTemplate中的TextBlock和TextBox。這是通過以下方式完成的:將樣式應用於DataTemplate中的元素

<UserControl.Resources> 
     <DataTemplate DataType="{x:Type Binding:StringBindingData}" x:Key="dataTemp"> 
      <StackPanel Orientation="Horizontal" Name="sPanel"> 
       <TextBlock Name="txtDescription" Text="{Binding Description}" /> 
       <TextBox Name="textboxValue" Text="{Binding Mode=TwoWay, Path=Value, UpdateSourceTrigger=PropertyChanged}" /> 
      </StackPanel> 
     </DataTemplate> 

    </UserControl.Resources> 

    <Grid> 
     <ItemsControl Name="textItemsControl" ItemsSource="{Binding}"/> 
    </Grid> 

我需要能夠在不同情況下對TextBlock/TextBox應用不同的樣式。例如,在某些情況下,我希望能夠對TextBlock應用白色Foreground或更改TextBox的寬度。

我已經嘗試了幾種不同的方法: 在正在使用的控制我已經爲TextBlock的樣式窗口:

<Style TargetType="{x:Type TextBlock}" > 
    <Setter Property="Foreground" Value="White" /> 
</Style> 

這個工作對窗口中的所有其他的TextBlocks。

我也嘗試使用

var myDataTemplate = (DataTemplate)this.Resources["dataTemp"]; 

得到的代碼隱藏在DataTemplate中,但無法得到任何進一步的應用樣式到所有的TextBlock元素。

+0

什麼是「不同的情況」? – Cybermaxs

+0

在一些窗口中,我需要TextBlock有一個白色的前景,並在其他人需要它有一個黑色的前景,例如 – binncheol

+1

這是一個很好的問題。提問者必須非常聰明,也很有吸引力。也可能應該得到一些額外的時間。 – DaveDev

回答

1

雖然我不確定你的要求。但是爲了從代碼中找到控制,我建議使用VisualTreeHelper。我一般用這個輔助函數來做我的東西 -

public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) 
    where T : DependencyObject 
{ 
    if(depObj != null) 
    { 
    for(int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 
    { 
     DependencyObject child = VisualTreeHelper.GetChild(depObj, i); 
     if(child != null && child is T) 
     { 
      yield return (T)child; 
     } 

     foreach(T childOfChild in FindVisualChildren<T>(child)) 
     { 
      yield return childOfChild; 
     } 
    } 
    } 
} 

用法:

foreach (var textBlock in FindVisualChildren<TextBlock>(this)) 
{ 
     /* Your code here */ 
} 
1

你看着「視覺美」。你可以在你的模板中設置不同的可見狀態,可以在代碼中分配。

檢出上一個問題What is a visual state ...

相關問題