【问题标题】:`<Run />` doesn't databind in designtime`<Run />` 在设计时没有数据绑定
【发布时间】:2015-05-18 10:38:50
【问题描述】:

我有一个从ReactiveObject 继承自reactiveui.net 的视图模型,类似于

public sealed class TestViewModel : ReactiveObject
{
    public sealed class NestedViewModel
    {
        private string _property;
        public string VMProperty
        {
            get { return _property; }
            set { this.RaiseAndSetIfChanged(ref _property, value); }
        }

        private string _suffix;
        public string Suffic
        {
            get { return _suffix; }
            set { this.RaiseAndSetIfChanged(ref _suffix, value); }
        }

    }

    private NestedViewModel _nested = new NestedViewModel();
    public Nested
    {
        get { return _nested; }¨
        set { this.RaiseAndSetIfChanged(ref _nested, value); }
    }

#if DEBUG
    public TestViewModel() {
        Nested.VMProperty = "Test string";
        Nested.Suffix = "with suffix";
    }
#endif
}

我可以得到以下内容来显示设计时和运行时:

 <Page.DataContext>
     <local:TestViewModel />
 </Page.DataContext>

 <TextBlock Text="{Binding Nested.VMProperty}" />
 <TextBlock Text="{Binding Nested.Suffix}" />

但是当我尝试这样做时,设计时没有显示任何文本:

 <Page.DataContext><!-- ... -->

 <TextBlock>
     <Run Text="{Binding Nested.VMProperty}" />
     <Run Text="{Binding Nested.Suffix}" />
 </TextBlock>

运行时它仍然可以工作,但我不想每次我想检查一些像素推送时都必须部署到设备模拟器......

如何让这些属性在设计时显示在 &lt;Run /&gt; 标记内?

【问题讨论】:

  • 这可能不是您所希望的,但是类似的案例已经为 WP7 here987654322@ 进行了讨论和回答
  • @AndersGustafsson 感谢您的提示,尽管它并不能解决我的问题。
  • 我用 DesighData 玩了一点,似乎 TextBlockRun 方法不起作用就像你在问题中提到的那样。另一件事是,当在 DataTemplate 中使用时,这种组合(TB 与 Run)将成功地在设计模式下工作 - 您可以查看 my sample - 请参阅 MainPage.xaml。
  • 你在哪里做view和viewmodel的联动。该视图假设使用 ViewFor... 如果您这样做,则 xaml 的使用已过时。你的想法?
  • @DeJaVo:我确实让页面实现了IViewFor&lt;T&gt;,但我不能让它继承ViewFor&lt;T&gt;,因为我还需要有自己的基类,而我一直无法使其与通用基类一起使用。此外,由于 VM 层的实现方式(由其他人实现,即不受我控制),有时我必须在 OnNavigatedTo 事件处理程序中分配视图模型。

标签: xaml windows-phone-8.1 reactiveui


【解决方案1】:

ReactiveUI 框架的创建者 Paul Betts 主张将示例数据硬编码到页面的 XAML 中:

<TextBlock>
 <Run Text="Test String" x:Name="VMproperty" />
 <Run Text="with suffix" x:Name="Suffix" />
</TextBlock>

然后您可以在页面后面的代码中进行绑定:

this.OneWayBind(ViewModel, vm => vm.VMproperty, v => v.VMproperty.Text);
this.OneWayBind(ViewModel, vm => vm.Suffix, v => v.Suffix.Text);

这些 ReactiveUI 样式绑定会覆盖在 XAML 中硬编码的示例数据。因此,您可以在设计时获取示例数据,并在运行时获取数据绑定。

来源:https://groups.google.com/d/msg/reactivexaml/GrVHWm8tUuM/4EAxOsxc_LQJ

【讨论】:

    【解决方案2】:

    在绑定中使用FallbackValue 怎么样?我经常使用它来检查绑定内容的外观并且没有任何问题。

    【讨论】:

    • 这是个好主意,但FallbackValue 也不会在设计时呈现任何东西...... :(
    • 做了更多的搜索,不幸的是 在设计时不起作用。我只需在 VM 上创建另一个属性,它将 VMProperty 和 Suffix 组合为单个字符串..
    • 不幸的是,在这个项目中,我无法控制 VM 层 - 它们使用 Xamarin 在多个平台之间共享。但由于似乎没有其他选择,我会看看能不能解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多