gpt4 book ai didi

C# Wpf 绑定(bind)不适用于标签

转载 作者:行者123 更新时间:2023-11-30 21:55:09 33 4
gpt4 key购买 nike

我试图在单击按钮时更改标签的内容,但它不起作用。如果我使用相同的代码来更改按钮的内容,我点击它就可以了。

这是我的代码:

<Window x:Class="TestGrila.Grila"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:view="clr-namespace:TestGrila.View"
xmlns:viewModel="clr-namespace:TestGrila.ViewModel"
xmlns:res="clr-namespace:TestGrila.Resources"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
WindowStartupLocation="CenterScreen"
Height="350" Width="532.463" Icon="Resources/icon.png">
<Window.DataContext>
<viewModel:IntrebariViewModel />
</Window.DataContext>

<Grid>
<Label
Content="{Binding Response,UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left" VerticalAlignment="Top" Margin="50,55,0,0"/>


<Button
Grid.Row="0"
Command="{Binding MyButtonClickCommand}"
Content="{x:Static res:Strings.Container_Button_MoveBack}" Margin="246,0,189,27" RenderTransformOrigin="0.054,0.495" Height="30" VerticalAlignment="Bottom" >
<Button.DataContext>
<viewModel:IntrebariViewModel/>
</Button.DataContext>
</Button>

<Button
Grid.Row="0"
Command="{Binding MoveNextCommand}"
Content="{x:Static res:Strings.Container_Button_MoveNext}" Height="30" VerticalAlignment="Bottom" Margin="361,0,75,27" >
<Button.DataContext>
<viewModel:IntrebariViewModel/>
</Button.DataContext>
</Button>

</Grid>

这是 View 模型的代码:

 public class IntrebariViewModel:INotifyPropertyChanged
{

string response;

public string Response {

get { return this.response; }

set {
if (this.response == value)
return;

this.response = value;
NotifyPropertyChanged("Response");
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}


public ICommand MyButtonClickCommand
{
get { return new DelegateCommand<object>(FuncToCall); }
}

private void FuncToCall(object context)
{

Response = "New content";

}
}

最佳答案

您正在创建 3 个独立的 View 模型实例。您应该从 xaml 中删除多余的 DataContext 行:

<Button
Grid.Row="0"
Command="{Binding MyButtonClickCommand}"
Content="{x:Static res:Strings.Container_Button_MoveBack}" Margin="246,0,189,27" RenderTransformOrigin="0.054,0.495" Height="30" VerticalAlignment="Bottom" >
<!-- Don't include this!!!!
<Button.DataContext>
<viewModel:IntrebariViewModel/>
</Button.DataContext>
-->
</Button>

这些会导致您的按钮拥有自己的 View 模型,并且无法在窗口的主视图模型上工作。

关于C# Wpf 绑定(bind)不适用于标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32530081/

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