首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何设置AppBar DataContext

如何设置AppBar DataContext
EN

Stack Overflow用户
提问于 2014-09-10 05:13:16
回答 2查看 264关注 0票数 0

据我所知,就好像什么都没挂上一样。文本框不会获取VM中的值或设置值,也不会在单击时点击按钮命令。

代码语言:javascript
复制
<Page.TopAppBar>
    <AppBar>
        <AppBar.DataContext>
            <Binding Path="AppBar" Source="{StaticResource Locator}"/>
        </AppBar.DataContext>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto"></ColumnDefinition>
                <ColumnDefinition Width="auto"></ColumnDefinition>
                <ColumnDefinition Width="auto"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <TextBox Margin="0,0,20,0" TextAlignment="Center" Height="25" Grid.Column="0" Text="{Binding IPAddress}"></TextBox>
            <TextBox Margin="0,0,20,0" TextAlignment="Center" Height="25" Grid.Column="1" Text="{Binding Port}"></TextBox>
            <Button Grid.Column="2" Command="{Binding SaveCommand}">Save</Button>
        </Grid>
    </AppBar>
</Page.TopAppBar>
<Page.DataContext>
    <Binding Path="Main" Source="{StaticResource Locator}"/>        
</Page.DataContext>
EN

回答 2

Stack Overflow用户

发布于 2014-09-10 22:31:33

你试过调试eventhandler AppBar.DataContextChanged吗?应用程序栏的datacontext最初设置为正确的值,但当再次执行更改的数据上下文并将新的datacontext设置为null时,它就会变坏。因此,我建议添加一个开关,以便在出现空值时恢复为正确的datacontext。

XAML

代码语言:javascript
复制
<AppBar DataContextChanged="AppBar_DataContextChanged" ... />

C#

代码语言:javascript
复制
    private object _dataContext;
    private void AppBar_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
    {
        if (args.NewValue != null)
        {
            if (_dataContext == null)
            {
                _dataContext = args.NewValue;
            }
        }
        else
        {
            if (_dataContext != null)
            {
                sender.DataContext = _dataContext;
            }
        }
    }

如果希望textbox更新视图模型,则绑定模式必须为TwoWay。

代码语言:javascript
复制
<TextBox Margin="0,0,20,0" TextAlignment="Center" Height="25" Grid.Column="0" Text="{Binding IPAddress, Mode=TwoWay}"></TextBox>
<TextBox Margin="0,0,20,0" TextAlignment="Center" Height="25" Grid.Column="1" Text="{Binding Port, Mode=TwoWay}"></TextBox>
票数 0
EN

Stack Overflow用户

发布于 2014-09-12 19:29:36

如果我没记错的话,Windows 8应用商店不支持应用程序栏中的绑定。

更多关于这里的讨论,http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a27c9c88-82c5-43fb-9fd9-6ae36dc39af6/appbar-databinding-does-not-work-because-datacontext-is-not-available?forum=winappswithcsharp

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25753649

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档