<ListBox x:Name="noteListBox"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch" Foreground="#FF329BD6" Margin="0,24,0,85">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock x:Name="noteTitle"
FontSize="40"
Text="{Binding Titolo}"
Tag="{Binding FileName}"
Foreground="#FF45B1EE" Tap="apriNota" Margin="5,0,0,0" />
<TextBlock x:Name="noteDateCreated"
Text="{Binding DateCreated}"
Margin="10,0,0,10" Foreground="#FF60ADD8" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我需要在TextBlocks
内动态更改这两个StackPanel
的前景颜色。问题是它们似乎无法通过我的C#代码访问,因为它们位于StackPanel
中。
基本上这就是我需要做的事情:
noteTitle.Foreground = new SolidColorBrush(Color.FromArgb(255, 50, 155, 214));
但我在C#代码中找不到noteTitle
...我该如何解决这个问题?
谢谢!
答案 0 :(得分:2)
我建议将值转换器用于此类目的。我假设前景值取决于你绑定的proeprties FileName
,DateCreated
的对象状态,所以只需将此对象用作converetr参数,并在转换器中进行主要计算以确定应返回哪个Foreground这个特别的项目。
public class EntityToForegroundConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
var entity = value as IMyEntity;
// TODO: determine a foreground value based on bound
// object proerrty values
}
public object ConvertBack(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return null;
}
}
<Control.Resources>
<src:EntityToForegroundConverter x:Key="foregroundConverter"/>
</Control.Resources>
<TextBlock
Foreground="{Binding Converter={StaticResource foregroundConverter}}" />
答案 1 :(得分:0)
如果你想要get元素,你可以使用这段代码: var a = noteListBox.ItemTemplate.LoadContent()as StackPanel; (a作为StackPanel).Background = Brushes.Red;
foreach (UIElement child in a.Children)
{
if (child is TextBlock)
if ((child as TextBlock).Name.CompareTo("noteDateCreated") == 0)
{
(child as TextBlock).Foreground = Brushes.Red;
}
}
或者您想要更改更改模板,您可以按代码创建模板,并覆盖模板:
DataTemplate template = new DataTemplate(typeof(Test)); FrameworkElementFactory spOuterFactory = new FrameworkElementFactory(typeof(StackPanel)); FrameworkElementFactory block1 = new FrameworkElementFactory(typeof(TextBlock)); FrameworkElementFactory block2 = new FrameworkElementFactory(typeof(TextBlock));
block1.SetValue(TextBlock.ForegroundProperty, Brushes.Red);
Binding binding1 = new Binding();
binding1.Path = new PropertyPath("Titolo");
block1.SetBinding(TextBlock.TextProperty, binding1);
block2.SetValue(TextBlock.ForegroundProperty, Brushes.Red);
Binding binding2 = new Binding();
binding2.Path = new PropertyPath("noteDateCreated");
block2.SetBinding(TextBlock.TextProperty, binding2);
spOuterFactory.AppendChild(block1);
spOuterFactory.AppendChild(block2);
template.VisualTree = spOuterFactory;
noteListBox.ItemTemplate = template;