Change the structure XAMLas follows
xmlns:local="clr-namespace:your_assembly_Name"
.....
<StackPanel>
<StackPanel.Resources>
<local:BackgroundConverter x:Key="backgroundConverter"/>
<Style TargetType="TextBlock">
<EventSetter Event="MouseDown" Handler="TextBlockMouseDownEvent" />
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource backgroundConverter}">
<Binding Path="Name" RelativeSource="{RelativeSource Self}"/>
<Binding Path="SelectedTextBlockName"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</StackPanel.Resources>
<TextBlock x:Name="text1" Text="Header"/>
<TextBlock x:Name="text2" Text="Header"/>
<TextBlock x:Name="text3" Text="Header"/>
<TextBlock x:Name="text4" Text="Header"/>
</StackPanel>
Use the following IMultiValueConverterand Add TextBlockMouseDownEventevent handler, as well as one DependencyPropertyin your code.
public string SelectedTextBlockName
{
get { return (string)GetValue(SelectedTextBlockNameProperty); }
set { SetValue(SelectedTextBlockNameProperty, value); }
}
public static readonly DependencyProperty SelectedTextBlockNameProperty =
DependencyProperty.Register("SelectedTextBlockName", typeof(string), typeof(Class_Name), new PropertyMetadata(null));
.......
private void TextBlockMouseDownEvent(object sender, MouseButtonEventArgs e)
{
TextBlock txtBlock = sender as TextBlock;
if (txtBlock != null)
{
SelectedTextBlockName = txtBlock.Name;
}
}
.......
public class BackgroundConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values[0] != null && values[1] != null && values[0].ToString() == values[1].ToString())
return new SolidColorBrush(Colors.Blue);
return new SolidColorBrush(Colors.White);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
If you want to set the default value to SelectedTextBlock, just set the TextBlock name that you want to select by default. eg:
SelectedTextBlockName = "text1";
source
share