我已经使用文本框和按钮实现了搜索功能。
当我在文本框中按Enter键或单击按钮时,按钮加载的图像会改变(即图像现在是search_next)。如果搜索文本发生变化,我希望为按钮加载上一个图像(搜索图像)。
这是我到目前为止所做的。
<Button x:Name="button1" Click="Button_Click">
<Image Source="..\Images\Search.ico" Height="13" Width="15"></Image>
</Button>
在文本框中按下按钮/ KeyUp事件 -
private void Button_Click(object sender, RoutedEventArgs e)
{
Image img = new Image();
img.Source = new BitmapImage(new Uri("Images/Search_next.ico",UriKind.RelativeOrAbsolute));
img.Stretch = Stretch.None;
button1.Content = img;
}
void searchTextBox_KeyUp(object sender, KeyEventArgs e)
{
Image img = new Image();
if (e.Key == Key.Enter)
{
img.Source = new BitmapImage(new Uri(@"/FunctionWizardControl;component/Images/Search_next.ico", UriKind.RelativeOrAbsolute));
img.Stretch = Stretch.None;
button1.Content = img;
}
}
我希望在文本更改时显示搜索图像。我想在KeyUp事件中添加一个else语句,但是每次用户输入文本框时都没有设置按钮的内容?如何实施此更改?
答案 0 :(得分:4)
使用具有2个属性的绑定:
public class YourViewModel : INotifyPropertyChanged
{
private string _searchString;
private string _imageSource;
public string SearchString
{
get { return _searchString; }
set
{
if (value == _searchString) return;
_searchString = value;
OnPropertyChanged();
ImageSource = @"/FunctionWizardControl;component/Images/Search_next.ico";
}
}
public string ImageSource
{
get { return _imageSource; }
set
{
// Only change image, if different than before
if (value == _imageSource) return;
_imageSource = value;
OnPropertyChanged();
}
}
// Implement INotifyPropertyChanged with method 'OnPropertyChanged'...
}
然后在XAML代码中,根据您的需要设置正确的绑定(例如,设置为LostFocus
(默认),因此不会检查每次按键:
<Button x:Name="button1" Click="Button_Click">
<Image Source="{Binding ImageSource}" Height="13" Width="15"/>
</Button>
<TextBox Text="{Binding SearchString, UpdateSourceTrigger=LostFocus}"/>