gpt4 book ai didi

c# - 在 WPF 中更改按钮图像的更好算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:37:57 25 4
gpt4 key购买 nike

我已经使用文本框和按钮实现了搜索功能。

当我在文本框中按回车键或单击按钮时,按钮加载的图像发生变化(即图像现在是 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 语句,但是每次用户在文本框中键入内容时,这不会设置按钮的内容吗?我如何实现此更改?

最佳答案

使用具有 2 个属性的绑定(bind):

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 代码中,根据您的需要设置正确的绑定(bind)(例如 LostFocus(默认),因此它不会检查每个按键:

<Button x:Name="button1" Click="Button_Click">
<Image Source="{Binding ImageSource}" Height="13" Width="15"/>
</Button>
<TextBox Text="{Binding SearchString, UpdateSourceTrigger=LostFocus}"/>

关于c# - 在 WPF 中更改按钮图像的更好算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27814287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com