2016-11-10 45 views
0

视图模型无法读取,即使单向模式设置

namespace My.ViewModels 
{ 
    public class ItemViewModel : ObservableObject 
    { 
     private ItemModel _model; 

     public ItemViewModel(ItemModel model) 
     { 
      _model = model; 
     } 

     public string Name { get { return _model.Name; } } 
    } 
} 

XAML只读属性

<UserControl x:Class="My.Controls.ItemControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:viewModels="clr-namespace:My.ViewModels" 
      mc:Ignorable="d" 
      d:DesignHeight="421" d:DesignWidth="786" 
      d:DataContext="{d:DesignInstance viewModels:ItemViewModel}"> 
    <Grid Background="White"> 
     <TextBlock><Run Text="Name:" /> <Run Text="{Binding Name, FallbackValue=Name, Mode=OneWay}" /></TextBlock> 
    </Grid> 
</UserControl> 

错误:

A TwoWay or OneWayToSource binding cannot work on the read-only property 'Name' 

我想做数据绑定到从我的ViewModel只读属性。 我已经设置绑定模式为单向..但它仍然会抛出上述错误。 我没有线索!任何帮助,将不胜感激。

+3

您确定这是唯一绑定到此属性的地方吗?如果您完全注释掉“TextBlock”,会发生什么? – dymanoid

+0

@Taelia,你的财产“名称”没有一个setter。这就是为什么你在TwoWay绑定时发生错误的原因。另外,据我所知,TextBlock不能被编辑。 –

+0

@dymanoid我......都对你在黑暗中拍摄的能力感到非常惊讶,并且有点尴尬,这很简单。在我的代码中的其他地方,我有一个剩余的引用,我没有应用Mode = Oneway。谢谢! – Taelia

回答

0

要使用OneWay绑定您的财产应该得到并设置。因此,在这种情况下,要解决问题,您只需将设置添加到您的属性中,如下所示:

public string Name { private set; get { return _model.Name; } 
+0

我希望底层类保持其只读属性,所以我想使用OneWay绑定,而不是双向绑定。感谢您的努力! – Taelia

+0

@Taelia我更新了答案。 –

相关问题