[英]Setting DataContext of an “Image” element inside button Click
我对数据绑定概念非常陌生,所以如果您觉得它很愚蠢,请原谅我的问题。 这个项目是为了学习一些 API 功能和 WPF 数据绑定。 但是,当我尝试通过将 WPF 中的图像元素的数据上下文设置为来自存储用于在屏幕上显示的图像路径的 Class 的属性来在屏幕上显示图标时,我遇到了这个问题。 我有以下图片:
<Image x:Name="imgWeatherIcon" Grid.Column="2" HorizontalAlignment="Left" Margin="380,134,0,0" VerticalAlignment="Top"
Width="90" Height="90" Source="{Binding ImgPath, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, diag:PresentationTraceSources.TraceLevel=High}">
<Image.DataContext>
<c:ConditionsNow/>
</Image.DataContext>
</Image>
我将 Source 绑定到一个属性,因此每当此属性更改时,我都会在屏幕上显示新的图标/图像。 问题是,只有在程序启动时(主窗口)设置了 DataContext 并且我需要它在按钮单击中才有效
这是有效的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ApiHelper.InitializeApiClient();
ConditionsNow conditionsObject = new();
imgWeatherIcon.DataContext = conditionsObject;
conditionsObject.ImgPath = @"https://developer.accuweather.com/sites/default/files/01-s.png";
}
请注意,“imgWeatherIcon”是 Label,我在其中显示图标/图像,并将其 DataContext 设置为属性“ImgPath”。 这只是为了澄清“imgWeatherIcon”,因为没有包含 WPF 代码,但如有必要,我可以这样做。
如果我每次启动应用程序时都这样做,则数据上下文会正确设置为 ImgPath 属性并在 UI 中更新。
但这是我需要它工作的地方,但不知道为什么它不起作用:
public ConditionsNow condObject = new();
private async void BtnCity_Click(object sender, RoutedEventArgs e)
{
imgWeatherIcon.DataContext = condObject;
condObject.ImgPath = @"G:\Visual Studio\Projects\Testing\AccuWeatherApp\accuweather-icon.jpg";
}
我知道我缺乏数据绑定和 WPF 的知识,但如果有人给我提示问题出在哪里,我将不胜感激。 我做了很多关于绑定等的研究,但仍然无法弄清楚。 顺便说一句,如果这对属性“ImgPath”有帮助,我已经实现了 INotifyPropertyChanged 以便能够跟踪更改。
您不应更改整个 DataContext 绑定。 您只需设置一次 DataContext,然后只更改绑定到 UI 的基础属性。 在您的情况下,您应该只更改 ImgPath 属性。 因此,从按钮单击事件中删除以下内容:
imgWeatherIcon.DataContext = condObject;
确保ConditionNow实现了INotifyPropertyChanged接口,以便在更改ImgPath的值时可以调用OnPropertyChanged()。 这是为了确保绑定会导致 UI 更改其呈现方式。
因此,您的 ConditionsNow class 应该具有类似于以下的形式:
public class ConditionsNow
{
private string _imgPath;
public string ImgPath
{
get => _imgPath;
set
{
_imgPath = value;
OnPropertyChanged();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.