需要将对象与窗口WPF中的文本块绑定

时间:2012-06-06 15:23:58

标签: wpf mvvm

我正在使用MVVM模式将entrylog绑定到文本块。

<Window.DataContext>
        <viewModel:WindowsEventsAutoMountViewModel x:Name="xWindowsEventsDetail"/>
    </Window.DataContext>
    <TextBlock x:Name="xCategoryTextBox" Grid.Column="1"  Grid.Row="0" TextAlignment="Center" Text="{Binding Path= xWindowsEventsDetail.Event.Category}"/> 

            <Label Grid.Row="1" Grid.Column="0" Content="{x:Static res:RecoveryManagerResources.EventDetailViewLabel_Level}" Name="xlabelLevel" ContentStringFormat="{}{0}:"/>
            <TextBlock x:Name="xLevelTextBox" Grid.Column="1"  Grid.Row="1" TextAlignment="Center" Text="{Binding Path= xWindowsEventsDetail.Event.Level}"/>

还有其他字段

但在字段中没有得到任何值

提前致谢

2 个答案:

答案 0 :(得分:0)

如果WindowsEventsAutoMountViewModel是您的类并且它设置为DataContext,则默认情况下绑定将引用该类的子项。

例如,如果您的类声明:

public class WindowsEventsAutoMountViewModel
{
    public string Name { get; set; }
}

您可以将其绑定为:

{Binding Path=Name}

只要将其设置为DataContext即可。基本上,从绑定中删除“xWindowsEventsDetail”。

如果要绑定到不是DataContext的资源,则需要在绑定到资源的Source属性中设置:

{Binding Path=Name, Source={StaticResource xWindowsEventsDetail}}

DataContext使您无需指定第二部分。

答案 1 :(得分:0)

你的道路错了。您应该直接绑定到DataContext,而不是元素。

<Window.DataContext>
        <viewModel:WindowsEventsAutoMountViewModel x:Name="xWindowsEventsDetail"/>
    </Window.DataContext>
    <TextBlock x:Name="xCategoryTextBox" Grid.Column="1"  Grid.Row="0" TextAlignment="Center" Text="{Binding Path=Event.Category}"/> 

            <Label Grid.Row="1" Grid.Column="0" Content="{x:Static res:RecoveryManagerResources.EventDetailViewLabel_Level}" Name="xlabelLevel" ContentStringFormat="{}{0}:"/>
            <TextBlock x:Name="xLevelTextBox" Grid.Column="1"  Grid.Row="1" TextAlignment="Center" Text="{Binding Path=Event.Level}"/>