only property even with OneWay mode set

ViewModel

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>

Error:

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

I'm trying to do DataBinding to a read-only property from my ViewModel. I've set the Binding Mode to OneWay.. yet it still throws the error above. I'm out of clues! Any help would be appreciated.


To use OneWay binding your property should has get and set. So in this case, to fix the problem you just add set to your property like this:

public string Name { private set; get { return _model.Name; } 
链接地址: http://www.djcxy.com/p/50474.html

上一篇: WPF全屏焦点问题?

下一篇: 即使使用单向模式设置也只有财产