【问题标题】:No DataContext found for binding TwoWay? [closed]找不到用于绑定 TwoWay 的 DataContext? [关闭]
【发布时间】:2023-01-29 21:41:35
【问题描述】:

我有一个用户控件,它有一个组件

<ItemsPanelTemplate>
 <Grid Name="WeekViewGrid"  Width="Auto" Height="Auto" HorizontalAlignment="Left"                                   
  local:GridSetUp.WeekView="{Binding TheWeek.Days, Mode=TwoWay}"
  local:GridSetUp.GridData="{Binding TheGridData,  Mode=TwoWay}"
  IsSharedSizeScope="True">
 </Grid>
</ItemsPanelTemplate>

其中 GridSetup.WeekView 和 GridSetUp.GridData 是两个附加属性。

Intellisense 下划线 TwoWay 并告诉我“没有找到用于绑定 TwoWay 的 DataContext” 绑定到 DataContext 的两个属性 TheWeek.Days 和 TheGridData 似乎没有任何问题。

那里发生了什么事?模式语法是否正确?为什么它试图从 Mode 属性中创建一个绑定表达式?如果它可能相关,我可以为附加属性和数据上下文的属性提供更多代码,但此时不想弄乱。 编辑:好的,这是有关附加属性的更多详细信息

public static  DependencyProperty WeekViewProperty = DependencyProperty.RegisterAttached( "WeekView", typeof(ObservableCollection<Day>), typeof(GridSetUp), new PropertyMetadata(new ObservableCollection<Day> { }, WeekViewChanged)); public static ObservableCollection<Day> GetWeekView(Grid grid)
 {
  return (ObservableCollection<Day>)grid.GetValue(WeekViewProperty);
 }
public static void SetWeekView(Grid grid, ObservableCollection<Day> value)
 {
            grid.SetValue(WeekViewProperty, value);
 }

public static  DependencyProperty GridDataProperty = DependencyProperty.RegisterAttached(
"GridData", typeof(GridData), typeof(GridSetUp), new PropertyMetadata(new GridData(), GridDataChanged));

public static GridData GetGridData(Grid grid)
 {
  return (GridData)grid.GetValue(GridDataProperty);
 }
  public static void SetGridData(Grid grid, GridData value)
 {
   grid.SetValue(GridDataProperty, value);
  }
  public static void GridDataChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
 {           
 }    

一切都按我预期的那样运行,但我不理解智能感知建议。它只是虚假的而不是麻烦吗?

【问题讨论】:

  • 这只是 XAML 设计器的抱怨。您可以分配一个设计时 DataContext。

标签: wpf


【解决方案1】:

分配设计时 Datacontext:

<Window x:Class="YourClass" xmlns:vm="clr-namespace:YourViewModel">
    <Window.DataContext>
        <vm:YourViewModel/>
    </Window.DataContext>
    <ItemsPanelTemplate>
        ETC...
    </ItemsPanelTemplate>
</Window>

问题仅在于设计时间。 这意味着,在您运行应用程序之前,数据上下文是未知的。 但是,您可以分配一个设计时数据上下文,如示例中所示,以避免此问题。

您甚至可以在设计时和运行时使用不同的数据上下文。可以方便地填充一个简单的设计时数据上下文以查看对 UI 的影响。

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 2015-03-14
    相关资源
    最近更新 更多