在 WPF 中更改按钮图像的更好算法
本文关键字:图像 更好 算法 按钮 WPF | 更新日期: 2023-09-27 18:36:36
>我已经用文本框和按钮实现了搜索功能。
当我在文本框中按回车键或单击按钮时,按钮加载的图像会更改(即图像现在已search_next)。如果搜索文本发生变化,我希望为按钮加载上一个图像(搜索图像)。
这就是我到目前为止所做的。
<Button x:Name="button1" Click="Button_Click">
<Image Source="..'Images'Search.ico" Height="13" Width="15"></Image>
</Button>
在文本框中的按钮单击/键向上事件时 -
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 语句,但这不会在用户每次在文本框中键入时设置按钮的内容吗?如何实施此更改?
使用具有 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}"/>