TextBlock的WPF属性绑定



我有一个弹出窗口,其中有一个texblock,我想将其绑定到ViewModel中的属性。我已经成功地在弹出窗口中绑定了一个布尔值,我基本上对字符串也做了同样的操作,但不知何故,字符串属性没有更新。。。

这是我的.xaml:

<Popup Margin ="10" HorizontalAlignment="Center" VerticalAlignment="Top" AllowsTransparency="True" IsOpen="{Binding OpenPopup}" Height="150" Width="300">
<Grid Background="#FFFFCCCC">
<TextBlock x:Name="NewVersionText" Margin="10,10,10,10" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Center" FontSize="14" Width="230">
Eine neue Version der Applikation ist verfügbar. <LineBreak /> Möchten Sie diese herunterladen?
</TextBlock>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="10,10,10,10" TextWrapping="Wrap" Width="230" Text="{Binding DownloadText}"/>
</Grid>
</Popup>

[EDIT]:点击以下按钮时,属性发生更改:

<Button Content="Ja" HorizontalAlignment="Left" Height="20" VerticalAlignment="Top" Width="70" Command="{Binding DownloadVersionCommand}"/>
<Button Content="Später" HorizontalAlignment="Left" Height="20" Margin="75,0,0,0" VerticalAlignment="Top" Width="70" Command="{Binding ClosePopupCommand}"/>

我成功绑定的属性是IsOpen中的OpenPopup="{Binding OpenPopup}",不起作用的是Text中的DownloadText="{Binding DownloadText}"。.xaml有一个ViewModel,它已经连接好了(正如我所说,它可以很好地与所有其他属性配合使用)。

我的ViewModel中的c#代码是:[Edit:两个属性都在同一个ViewModel]对于文本字符串:

private string _downloadText;
public string DownloadText {
get {
return _downloadText;
}
set {
_downloadText = value;
Debug.WriteLine("DownloadText = " + value);
RaisePropertyChanged();
}
}

private void DownloadVersion() {
DownloadText = "Download gestartet";
VersionManager.downloadFile();

对于弹出布尔值:

private bool _openPopup;
public bool OpenPopup {
get {
return _openPopup;
}
set {
_openPopup = value;
Debug.WriteLine("Open Popup = " + value);
RaisePropertyChanged();
}
}
private void ClosePopoup() {
OpenPopup = false;
}

RaisePropertyChanged()方法的实现方式如下:

public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string propertyName = null) {
if (PropertyChanged == null)
return;
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
Debug.WriteLine("MainWindowViewModel, PropertyChanged: " + propertyName);
}
}

当调用ClosePopup()方法时,属性会发生变化,这会导致弹出窗口的IsOpen属性变为false并关闭。。正如它应该做的那样。

当调用DownloadVersion()方法时,属性DownloadText也被成功更改,但在我的视图中没有更新。有什么建议我缺少的吗?

[EDIT]:按钮的绑定:

public ICommand DownloadVersionCommand {
get; set;
}
// In the ViewModel Constructor:
DownloadVersionCommand = new RelayCommand(o => {
Debug.Write("DownloadVersionCommand " + o);
DownloadVersion();
})

您可以尝试在后台线程上调用VersionManager.downloadFile()

private void DownloadVersion() {
DownloadText = "Download gestartet";
Task.Run(() => VersionManager.downloadFile());
}

或者出于测试目的暂时只是注释掉或删除下载调用:

private void DownloadVersion() {
DownloadText = "Download gestartet";
}

那么它应该会起作用。

不能在同一个线程上同时更新TextBlock和下载文件。

最新更新