在WPF中绑定我不断变化的数据上下文

时间:2013-05-14 17:25:46

标签: c# wpf

我已经看到这个请求略有不同 - 但我很难让这个为我的生活工作。我有一个应用程序,用户选择组合框将驱动一个事件。甚至从数据库中抓取数据,我想将这些数据绑定到UI。我以为我的绑定设置是正确的,但我无法发生任何事情。我可以看到所有代码计算正确触发,但我没有看到任何关于绑定的反馈。我是WPF的新手,仍然试图绕过它(我来自MVC网络世界)所以任何指针都非常感激。谢谢。

MainWindow Code背后:

public MainWindow()
{
    InitializeComponent();
    DataContext = new MainWindowViewModel();
}

private void cboAllClients_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MainWindowViewModel vm = DataContext as MainWindowViewModel;
    listClient selectedClient = e.AddedItems[0] as listClient;
    Credit.Calc c = new Credit.Calc();
    c.CalcCredit(selectedClient.ClientName);
    vm.FFCredits = c.FundFamilyCredits;
    vm.FundCredits = c.FundCredits;
    DataContext = vm;
}

主窗口xaml(缩写为绑定问题)

<ListBox x:Name="lbFundFamily" Width="auto" Height="auto"
         Background="Transparent" BorderThickness="0">
    <ListBox.DataContext>
        <Binding Source="FFCredits"></Binding>
    </ListBox.DataContext>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="20"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="auto"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding Path=FundFamilyName}"
                           Grid.Row="0" Grid.Column="0"
                           Background="White" FontSize="14" Foreground="Black">
                </TextBlock>
                <!--<Rectangle Width="{Binding Path=BrokerCreditList.Utilization}"
                               Height="20" Grid.Row="0" Grid.Column="1"></Rectangle>-->
                <!--<TextBlock Text="{Binding Path=BrokerCreditList.}"></TextBlock>-->
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


MainWindowViewModel:

class MainWindowViewModel : BaseViewModel
{
    public List<listClient> AllClients { get; set; }
    public ObservableCollection<FundFamilySum> FFCredits { get; set; }
    public ObservableCollection<FundSum> FundCredits { get; set; }

    public MainWindowViewModel()
    {
        using (AgencyModelEntities db = new AgencyModelEntities())
        {
            AllClients = db.listClients.ToList();
            FFCredits = new ObservableCollection<FundFamilySum>();
            FundCredits = new ObservableCollection<FundSum>();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

最初加载视图时,ListBox绑定到vm.FFCredits new ObservableCollection<FundFamilySum>();

但视图不知道FFCredits已更改,除非引发PropertyChanged通知,因此它仍然绑定到new ObservableCollection<FundFamilySum>();

我认为您希望在再次设置DataContext = vm时获取更改。但这不起作用,因为vm已经是DataContext