gpt4 book ai didi

c# - MVVM 绑定(bind)在设计时不起作用

转载 作者:行者123 更新时间:2023-11-30 15:24:58 25 4
gpt4 key购买 nike

我试图将几个按钮的可见性绑定(bind)到 View 模型中的一些 bool 值,并使其在设计时工作。我这样做了好几次,从来没有遇到过问题,但现在它不起作用了,我也不知道为什么。请注意,一切正常当我运行应用程序时很好。

我将精华提取到一个单独的应用程序中,但它仍然不起作用!

我的 XAML:

<Window x:Class="BindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:bindingTest="clr-namespace:BindingTest"
Title="MainWindow" Height="350" Width="525"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance bindingTest:TestViewModel, d:IsDesignTimeCreatable=true}">
<Grid>
<Grid.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis"/>
</Grid.Resources>
<StackPanel>
<Button Visibility="{Binding IsButton1Visible, Converter={StaticResource BoolToVis}}">Hallo 1</Button>
<Button Visibility="{Binding Button2Visibility}">Hallo 2</Button>
<Button>Hallo 3</Button>
</StackPanel>
</Grid>
</Window>

我的 View 模型:

public class TestViewModel
{
public bool IsButton1Visible
{
get { return true; }
}

public Visibility Button2Visibility
{
get { return Visibility.Hidden; }
}
}

为了让它在真正的应用程序中工作,我添加到 XAML 的构造函数中:

DataContext = new TestViewModel();

这一切都非常简单,但为什么它在设计器中不起作用??我过去总是让它工作,现在我尝试了几个小时......这不是唯一不起作用的绑定(bind),但为什么连这个都不起作用??

预期结果:

  • Button1 可见
  • Button2 隐藏
  • Button3 可见

设计器中的结果:

  • 按钮 1 折叠
  • Button2 可见
  • Button3 可见

最佳答案

更新:设计时 DataContext 绑定(bind)不起作用的问题是由于错误地为 IsDesignTimeCreatable 属性使用了 d: 命名空间前缀.

所以,改变

d:IsDesignTimeCreatable=True

IsDesignTimeCreatable=True

一切都会好起来的。 (我向 MS 提交的错误报告也将使用此信息进行更新。)


IsDesignTimeCreatabled: 命名空间为前缀时,设计时 DataContext 绑定(bind)不起作用的问题在 VS2015 和 VS2013 中始终可重现(请参阅评论在问题下方),我决定向 Microsoft 提交错误报告:Issue #1651633 "WPF designer: Designtime DataContext bindings broken?" .

让我们看看微软将如何跟进这个问题。它应该得到解决,因为这样的问题会让开发人员措手不及,并让他重新安装 Visual Studio 而没有任何好处......;)

关于c# - MVVM 绑定(bind)在设计时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31924044/

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