你需要使用价值转换器吗?我使用 MVVM 模式快速尝试了这个,效果很好。如果你可以使用 MVVM,你可以这样做:
主页.xaml
<UserControl x:Class="BindBoldText.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindBoldText"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.DataContext>
<local:MainPage_ViewModel/>
</UserControl.DataContext>
<StackPanel>
<TextBlock Text="{Binding Value1, Mode=TwoWay}"/>
<TextBlock Text="{Binding Value2, Mode=TwoWay}" FontWeight="{Binding Value2FontWeight}"/>
<TextBox Text="{Binding Value2, Mode=TwoWay}" TextChanged="TextBox_TextChanged"/>
</StackPanel>
MainPage.xaml.cs
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.viewModel = this.DataContext as MainPage_ViewModel;
}
private MainPage_ViewModel viewModel;
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
viewModel.Value2 = (sender as TextBox).Text;
}
}
MainPage_ViewModel.cs
public class MainPage_ViewModel : INotifyPropertyChanged
{
public string Value1
{
get { return value1; }
set
{
if (value1 != value)
{
value1 = value;
OnPropertyChanged("Value1");
}
}
}
private string value1 = "Test";
public string Value2
{
get { return value2; }
set
{
if (value2 != value)
{
value2 = value;
OnPropertyChanged("Value2");
OnPropertyChanged("Value2FontWeight");
}
}
}
private string value2 = "Test";
public FontWeight Value2FontWeight
{
get
{
if (value2.Equals(value1))
{
return FontWeights.Normal;
}
else
{
return FontWeights.Bold;
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}