【问题标题】:Bidning with TextBlock is not Working与 TextBlock 绑定不起作用
【发布时间】:2013-01-11 07:32:51
【问题描述】:

我的模型为:

namespace Forecast.MVVM.WPF.ViewModel
{
    public class ApplicationInfoViewModel
    {
       private string versionNumber;
       public ApplicationInfoViewModel()
        {
          versionNumber = Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
       public string VersionNumber
        {
            get { return versionNumber; }
            set { versionNumber = value; }
        }
}

我认为我正在设置 datContext 并将值设置为 ;

<UserControl .... xmlns:AppInfo="clr-namespace:Forecast.MVVM.WPF.ViewModel" .../>
 <UserControl.Resources>
        <AppInfo:ApplicationInfoViewModel x:Key="forecastVersionInfo"/>
    </UserControl.Resources>
<Grid>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding VersionNumber}" VerticalAlignment="Bottom"/>
</Grid>

但我看不到值

【问题讨论】:

    标签: wpf c#-4.0 data-binding binding


    【解决方案1】:

    第一种方式:

    尝试将&lt;UserControl.Resources&gt; 替换为&lt;UserControl.DataContext&gt; ...并删除“x:Key="forecastVersionInfo"”。

    第二种方式: 或者在你的文本块上设置DataContext="{StaticResource forecastVersionInfo}"

    第三种方式: 根据this MSDN page,在您的文本块绑定上设置 Source 属性:

    Text="{Binding VersionNumber, Source={StaticResource forecastVersionInfo}}"
    

    【讨论】:

    • ,@Tilak, 如果我想通过使用 .ResourceOnly 来实现这一目标
    【解决方案2】:

    你没有设置 DataContext

    <UserControl.DataContext>
       <AppInfo:ApplicationInfoViewModel />
    </UserControl.DataContext>
    

    如果要引用资源,可以在Grid 上设置它或将资源移动到App.Resources 并在UserControl 上应用DataContext 作为属性

    <Grid DataContext="{Binding Path={StaticResource forecastVersionInfo}}">
        <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding VersionNumber}" VerticalAlignment="Bottom"/>
    </Grid>
    

    【讨论】:

      猜你喜欢
      • 2014-08-25
      • 2014-09-07
      • 2017-11-18
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2019-01-29
      • 2015-06-10
      • 1970-01-01
      相关资源
      最近更新 更多