c# Wpf绑定不支持标签
本文关键字:标签 不支持 绑定 Wpf | 更新日期: 2023-09-27 18:12:18
我试图改变一个标签的内容,当一个按钮被点击,但它不起作用。如果我用同样的代码来改变按钮的内容,我点击它的工作。
这是我的代码:
<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 Model的代码:
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个独立的视图模型实例。您应该从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>
这些导致你的按钮有自己的视图模型,而不是在主窗口上工作。