C#Wpf绑定不适用于标签

时间:2015-09-11 18:36:55

标签: c# wpf

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

这是我的代码:

<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>

这是视图模型的代码形式:

 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"; 

    }
  }

1 个答案:

答案 0 :(得分:3)

您正在创建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>

这些会导致您的按钮拥有自己的视图模型,而不适用于窗口的主视图。