【发布时间】:2019-01-17 17:56:02
【问题描述】:
我有一个相当复杂的表单,其中包含几个文本块。我想为这些块添加一个绑定,以便当鼠标悬停在它们上面时,所有其他文本与我悬停在上面的运行匹配的块都会突出显示。
如果您选择了一个单词,这与您在 Visual Studio 或 notepad++ 中看到的效果相同(所有相同的单词都会在编辑器窗口中突出显示)。
这是我目前所拥有的:
class TestViewModel
{
public string TextToMatch { get; set; }
}
public partial class Test : UserControl
{
TestViewModel _viewModel;
public Test()
{
_viewModel = new TestViewModel();
DataContext = _viewModel;
InitializeComponent();
}
private void Test_MouseEnter(object sender, MouseEventArgs e)
{
var text = ((TextBlock)sender).Text;
_viewModel.TextToMatch = text;
}
private void Test_MouseLeave(object sender, MouseEventArgs e)
{
_viewModel.TextToMatch = "";
}
}
部分 XAML:
<StackPanel>
<TextBlock
Name="Test1"
Background="{Binding TextToMatch Converter={StaticResource converter}}"
MouseEnter="Test_MouseEnter"
MouseLeave="Test_MouseLeave">
This matches
</TextBlock>
<TextBlock
Name="Test2"
Background="{Binding TextToMatch Converter={StaticResource converter}}"
MouseEnter="Test_MouseEnter"
MouseLeave="Test_MouseLeave">
This matches
</TextBlock>
<TextBlock
Name="Test3"
Background="{Binding TextToMatch Converter={StaticResource converter}}"
MouseEnter="Test_MouseEnter"
MouseLeave="Test_MouseLeave">
Some other text
</TextBlock>
<TextBlock
Name="Test4"
Background="{Binding TextToMatch Converter={StaticResource converter}}"
MouseEnter="Test_MouseEnter"
MouseLeave="Test_MouseLeave">
This matches
</TextBlock>
<TextBlock
Name="Test5"
Background="{Binding TextToMatch Converter={StaticResource converter}}"
MouseEnter="Test_MouseEnter"
MouseLeave="Test_MouseLeave">
Some other text
</TextBlock>
</StackPanel>
似乎很清楚,我需要一个用于这些绑定的值转换器。那不是问题。问题是如何将每个文本块的当前文本值获取到值转换器,以便它可以执行必要的文本比较并输出正确的背景颜色。
我该怎么做呢?或者有没有更好的方法我没有想到?
【问题讨论】:
标签: c# wpf mvvm data-binding valueconverter