【问题标题】:Caliburn.Micro - Binding a button in a sidebar to a method in a ViewModelCaliburn.Micro - 将侧边栏中的按钮绑定到 ViewModel 中的方法
【发布时间】:2015-03-20 05:25:09
【问题描述】:

我在绑定位于我的 Windows Phone 应用程序侧边栏中的按钮时遇到问题。按钮绑定似乎消失了..

这是我现在的代码

 <Grid x:Name="LayoutRoot" Background="Transparent">

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

        <sidebar:SidebarControl x:Name="sidebarControl"
                            HeaderText="WP"
                            HeaderBackground="YellowGreen"
                            HeaderForeground="White"
                            SidebarBackground="{StaticResource PhoneChromeBrush}">

            <sidebar:SidebarControl.SidebarContent>
                <Grid  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="380">


                    <Button Content="Go to page 2"  x:Name="GoToPage2"/>

                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>

                </Grid>


            </sidebar:SidebarControl.SidebarContent>

            <Grid VerticalAlignment="Top" HorizontalAlignment="Stretch"
              Margin="12">
                <TextBlock Style="{StaticResource PhoneTextNormalStyle}">Your current view goes here</TextBlock>
            </Grid>
        </sidebar:SidebarControl>



    </Grid>

</Grid>

目前我正在为侧边栏使用一个名为 SidebarWP8 的 nuget。也许 Calinbrun.Micro 不适用于这个?还是我必须在网格中插入与 VM 的绑定?

ViewModel 中的方法如下:

private readonly INavigationService navigationService;

public MainPageViewModel(INavigationService navigationService)
{
  this.navigationService = navigationService;
}

public void GoToPage2()
{
   navigationService.UriFor<Page2ViewModel>().Navigate();
}

【问题讨论】:

  • 究竟是什么在那里不起作用?您的按钮没有分配点击处理程序,只是一个名称。您必须添加 Click="..." 或命令。
  • 根据 Caliburn.Micro 的文档,如果 x:="exampleName" 与方法名相同,它应该可以工作吗?该按钮在侧边栏范围之外工作,但当它在范围内时,绑定不再工作。它不调用该方法。无论如何感谢您的回答:)

标签: c# windows-phone-8 mvvm caliburn.micro


【解决方案1】:

&lt;Button cm:Message.Attach="[Event Click] = [Action GoToPage2()]" /&gt;

这应该可以工作,因为其他评论者对默认控件是正确的...自定义控件需要添加更多处理,这可能会让人头疼,但使用 CM 上方的简写会看起来为按钮中的该属性并进行相应的处理。

【讨论】:

  • 鉴于您使用的是默认事件和操作,这可以简化为 Message.Attach="GoToPage2"。
【解决方案2】:

我检查了 Caliburn Micro 的源代码:我通过遍历可视化树来查找具有名称的元素来处理约定绑定。但它只检查每个控件的默认 Content 属性。

这意味着它只会通过 ContentChildren 元素,而不是像 SidebarContent 这样的自定义属性,因此不会找到命名元素在那里。

您必须手动连接它(通过绑定命令或添加 click 处理程序)。

【讨论】:

  • 好的!太感谢了!我会调查的。
  • 使用 CM 和 MVVM,您无需执行点击处理程序...这一切都在关联视图的视图模型中完成。
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 2011-05-01
  • 2013-04-27
  • 2012-04-21
  • 2021-05-09
  • 2014-05-12
  • 1970-01-01
相关资源
最近更新 更多