视图模型无法读取,即使单向模式设置
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只读属性。 我已经设置绑定模式为单向..但它仍然会抛出上述错误。 我没有线索!任何帮助,将不胜感激。
您确定这是唯一绑定到此属性的地方吗?如果您完全注释掉“TextBlock”,会发生什么? – dymanoid
@Taelia,你的财产“名称”没有一个setter。这就是为什么你在TwoWay绑定时发生错误的原因。另外,据我所知,TextBlock不能被编辑。 –
@dymanoid我......都对你在黑暗中拍摄的能力感到非常惊讶,并且有点尴尬,这很简单。在我的代码中的其他地方,我有一个剩余的引用,我没有应用Mode = Oneway。谢谢! – Taelia