数据绑定ObservableCollection< T>到Datagrid不工作 [英] Databinding ObservableCollection<T> to Datagrid not working

查看:90
本文介绍了数据绑定ObservableCollection< T>到Datagrid不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新现在我想我已经缩小了问题。
我创建单个类

Update Now I think I have narrowed the problem. I created single class

public class OptionStrike
{
    public OptionStrike(double p1, double p2, int p3)
    {
        // TODO: Complete member initialization
        P_OI = p1;
        StrikePrice = p2;
        P_Volume = p3;
    }

    public OptionStrike()
    {
        // TODO: Complete member initialization
    }

    public double P_OI { get; set; }
    public double P_Volume { get; set; }
    public double StrikePrice { get; set; }
}

现在,如果我将值加载到此OptionStrike作为

Now, if i load the values to this OptionStrike as

private void Test(object obj)
{
    oOs = new ObservableCollection<OptionStrike>(new OptionStrike[]
    {
        new OptionStrike(4201, 7500.00, 12345),
        new OptionStrike(818859, 7500.00, 123),
        new OptionStrike(84545, 8000.00, 23645),
        new OptionStrike(8889955, 8000.00,99999)
    });
}

它显示在窗口的datagrid中,但如果我这样做:

it shows in the datagrid in the window, but if I do it like this:

    _oOC = new ObservableCollection<OptionStrike>();
    OptionStrike os = new OptionStrike();
    os.StrikePrice=7500;
    os.P_Volume=545;
    os.P_OI=45454;
    _oOC.Add(os);
    os.StrikePrice = 7600;
    os.P_Volume = 5566;
    os.P_OI = 45455;
    _oOC.Add(os);

datagrid为空..

The datagrid is blank..

现场oOC是完全填充的,我已经检查了,但它仍然没有显示在Datagrid ...任何建议...

The field oOC is populating allright, and I have checked it, but it is still not showing in the Datagrid... Any suggestions...

oOC被声明为

private ObservableCollection<OptionStrike> _oOC;
public ObservableCollection<OptionStrike> oOC
{
    get { return _oOC; }
    set
    {
        if (value != _oOC)
        {
            _oOC = value;
            OnPropertyChanged(new PropertyChangedEventArgs("oOC"));
        }
    }
}

/ strong>我有一个ObservableCollection,我试图绑定到一个DataGrid ..

Old Question I have an ObservableCollection which I am trying to bind to a DataGrid..

private ObservableCollection<Option> _optionChain = new ObservableCollection<Option>();
public ObservableCollection<Option> OptionChain
{
    get { return _optionChain; }
    set
    {
        if (value != _optionChain)
        {
            _optionChain = value;
            PropChanged("OptionChain");
        }
    }
}

我的OptionChain集合正在填充像

My OptionChain collection is being populated like

private void ProcessOptionsData()
{
    OptionChain = d.ProcessOptionChainData(OptionChainHtmlElement, Ticker, Expiry);
}

期权类有

public string type;             // option typ (put/call)
public string stock;            // option stock ticker
public string symbol;           // option symbol
public double strike;           // option strike price

而XAML是

<DataGrid ItemsSource="{Binding OptionChain}" AutoGenerateColumns="False" DataContext="{Binding Mode=Default}">
  <DataGrid.Columns>
    <DataGridTextColumn Header="Type" Binding="{Binding type}" />
    <DataGridTextColumn Header="Strike" Binding="{Binding strike}" />
  </DataGrid.Columns>
</DataGrid>

现在没有填充Datagrid。我试过 AutoGenerateColumn =True,但无济于事...还尝试DataGridTextColumn绑定到 Option.strike 和所以,但是不成功..

Now the Datagrid is not being populated. I tried AutoGenerateColumn="True", but to no avail... also tried DataGridTextColumn Binding to Option.strike and so on, but was unsuccessful..

我在哪里出错?

(我正在使用ViewModelLocator)

(I am using ViewModelLocator)

修改

现在我已经清除了一切..只有一个文本框和一个标签。当我在文本框中写东西时,它没有被反映在标签中..代码是

Edit
Now i have cleared everything.. Just have one textbox, and one label. When i write something in textbox, it is not being reflected in label.. code is as

public class MainViewModel : INotifyPropertyChanged
    {
        #region Fields

        private string _ticker;
        public string Ticker
        {
            get { return _ticker; }
            set
            {
                if (value != _ticker)
                {
                    _ticker = value;
                    OnPropertyChanged("Ticker");
                }
            }
        }

        private string _status;
        public string Status
        {
            get { return _status;}
            set
            {
                if (value!=_status)
                {
                    _status = value;
                    OnPropertyChanged("Status");
                }
            }
        }

        public string PostBack
        {
            get { return string.Format("{0}, for expiry at ", Ticker); }
        }
        #endregion Fields

        public event PropertyChangedEventHandler PropertyChanged;
        // Create the OnPropertyChanged method to raise the event 
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }

`
MainWindow的XAML就像

` MainWindow's XAML is like

<Grid>
  <StackPanel Orientation="Horizontal">
    <TextBox Background="Transparent" Foreground="White" Text="{Binding Ticker}" HorizontalContentAlignment="Left" Width="150" VerticalContentAlignment="Center" Height="28" FontSize="18" Margin="10,0,0,0" />
    <Label Content="{Binding PostBack}" Width="250" Height="28" Margin="10,0,0,0" />
  </StackPanel>
</Grid>

MainWindow的代码正在用于datacontext ..

Codebehind of MainWindow is being used for datacontext..

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        MainViewModel mvm = new MainViewModel();
        this.DataContext = mvm;
    }
}


推荐答案

提供的新代码,您似乎只需要为 PostBack 属性添加一个PropertyChanged通知。

With the new code provided, it looks like you'd just need to add a PropertyChanged notification for the PostBack property.

由于该属性已被计算,它将不会自动重新计算,除非您通知它更改。你应该在 Ticker setter中这样做,因为PostBack取决于它的值。像这样:

Since that property is calculated, it won't be recalculated automatically unless you notify it's changed. And you should do so in the Ticker setter because PostBack depends on its value. Like this:

    private string _ticker;
    public string Ticker
    {
        get { return _ticker; }
        set
        {
            if (value != _ticker)
            {
                _ticker = value;
                OnPropertyChanged("Ticker");
                OnPropertyChanged("PostBack");
            }
        }
    }

这样,每次你在您的TextBox上输入一些内容,您会通知该视图PostBack的值已更改,并且必须刷新Label的Binding。

That way, every time you type something on your TextBox, you'll notify the view that PostBack's value has changed too, and that it has to refresh the Label's Binding.

哦,顺便说一句, TextBox的默认绑定将 UpdateSourceTrigger 设置为 LostFocus ,我想。如果您希望每次在写入文本时更新Label,而不必等待离开TextBox,您可能需要将其设置为 PropertyChanged (甚至使用延迟以获得更好的表现):

Oh, by the way, TextBox's default Bindings have UpdateSourceTrigger set to LostFocus, I think. If you want the Label to be updated every time you write something without having to wait for leaving the TextBox, you might want to set it to PropertyChanged (and even use a Delay for better performance):

<TextBox Background="Transparent"
         Foreground="White"
         Text="{Binding Ticker, UpdateSourceTrigger=PropertyChanged, Delay=1000}"
         HorizontalContentAlignment="Left"
         Width="150"
         VerticalContentAlignment="Center"
         Height="28"
         FontSize="18"
         Margin="10,0,0,0" />

这篇关于数据绑定ObservableCollection&lt; T&gt;到Datagrid不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆