【问题标题】:How to fix Binding TextBlock in WPF MVVM?如何修复 WPF MVVM 中的绑定 TextBlock?
【发布时间】:2019-04-07 14:54:19
【问题描述】:

您在底部看到我的 XAML 代码;当我在运行时调试它时,我在窗口的 StackPanel 的两个 TextBlocks 中什么都看不到,而在运行时绑定的 TextBlocks 中有一些数据! 为什么我在这些 TextBlock 中什么都看不到?

<Grid Name="SchoolGridView"
      AutomationProperties.AutomationId="SchoolGridView"
      AutomationProperties.Name="School Group" >
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="auto"/>
    </Grid.RowDefinitions>
    <ListView Grid.Row="0" Height="Auto"  x:Name="List" 
     HorizontalContentAlignment="Center" ItemsSource="{Binding 
     PeopleList}" SelectionMode="Single">

           ...
    </ListView>
    <StackPanel Background="LightGray" Height="60" 
       Orientation="Horizontal"  VerticalAlignment="Bottom" Grid.Row="1" 
       Visibility="{Binding 
       IsDetailVisible,UpdateSourceTrigger=PropertyChanged}">
            <StackPanel HorizontalAlignment="Left" Width="320">
                <TextBlock  Height="20" Text="asaasdasd"></TextBlock>
                <TextBlock  Height="20" HorizontalAlignment="Left" 
         Background="Yellow" Text="{Binding DataContext.FullName, 
         UpdateSourceTrigger=PropertyChanged}"/>
                <TextBlock  Height="20" HorizontalAlignment="Left" 
           Background="Yellow" Text="{Binding 
           DataContext.RowSelectedItem, 
             UpdateSourceTrigger=PropertyChanged}"/>
            </StackPanel>
            <WrapPanel HorizontalAlignment="Right">
                <Button  Content="DELETE" HorizontalAlignment="Right" 
             VerticalAlignment="Top"
                         Width="auto"  Height="50" Margin="3" Command=" 
             {Binding DataContext.DeleteCommand, ElementName=List}" 
             CommandParameter="{Binding SelectedItem, 
             ElementName=List}"/>
            </WrapPanel>
       </StackPanel>
     </Grid>
   </Window>

【问题讨论】:

  • 带有文本“asaasdasd”的TextBlock 不是数据绑定的。你看到了吗?
  • 是的,我明白了;我故意用它来测试它,但我正在努力与其他数据受限的。
  • 更多代码会很有帮助,尤其是如何将 ViewModel 绑定到 View。

标签: wpf xaml user-interface mvvm binding


【解决方案1】:

你必须填写DataContext

<Window x:Class="SampleApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">

或者在代码中设置

 DataContext = new ViewModel();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-14
    • 2018-05-23
    • 2013-04-04
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多