【发布时间】:2017-03-24 17:20:47
【问题描述】:
视图模型
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 中的只读属性进行 DataBinding。 我已将绑定模式设置为 OneWay.. 但它仍然会引发上述错误。 我没有线索了!任何帮助将不胜感激。
【问题讨论】:
-
你确定这是你唯一绑定到这个属性的地方吗?如果你完全注释掉
TextBlock会发生什么? -
@Taelia,您的属性“名称”没有设置器。这就是为什么在 TwoWay 绑定时会出现该错误的原因。另外,据我所知,TextBlock 无法编辑。
-
@dymanoid 我.. 对你在黑暗中拍摄的能力感到非常惊讶,但有点尴尬,事情就是这么简单。在我的代码中的其他地方,我有一个没有应用 Mode=Oneway 的剩余引用。谢谢!
标签: c# wpf data-binding