开发者

How to access property into XAML

开发者 https://www.devze.com 2023-02-03 20:06 出处:网络
I am a newbie in WPF As mention I have property in class public ObservableCollection<Company> GetCompany

I am a newbie in WPF As mention I have property in class

public ObservableCollection<Company> GetCompany
        {
            get
            {
                return _collectionCompany;
            }
        }

How can I access it in XAML? I am trying like this开发者_如何学Go:

<DataGridComboBoxColumn Header="Company" ItemsSource="{StaticResource GetCompany}"  Width="200"></DataGridComboBoxColumn>

But it gives an error.


first you need to allow the xaml to access the property by setting it's DataContext:

if the property is in the codebehind, add this to the window element:

DataContext="{Binding RelativeSource={RelativeSource self}}"

else if it's in a separate viewModel class (the preferred method)

public MainWindow()
{
    MainWindowViewModel viewModel = new MainWindowViewModel();
    this.DataContext = viewModel;

    InitializeComponent();
}

this viewmodel should implement INotifyPropertyChanged if you wan't the UI to be updated when the property changes (I assume so), however if the UI is to only have write access to the property this isn't necessary.

class MainWindowViewModel : INotifyPropertyChanged
{       
    ObservableCollection<Company> _company;
    public ObservableCollection<Company> Company
    {
        get
        {
            return _company;
        }
        set
        {
            if ( _company != value )
            {
                _company = value;
                RaisePropertyChanged( "Company" );
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged( string name )
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if ( handler != null ) handler( this, new PropertyChangedEventArgs( name ) );
    }

Just on a side note, try to avoid GetCompany & SetCompany as property names, instead use this.Company to differentiate it from the class name.


<DataGridComboBoxColumn Header="Company" ItemsSource="{Binding GetCompany}"  ...

However you must look that this property is accessible through the markup. If the property is defined in your code-behind, you can write in the constructor:

DataContext=this;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号