开发者

Binding in code question

开发者 https://www.devze.com 2023-02-07 12:54 出处:网络
I am using the same window that serves two purposes. Inside my window, i have a listview that I want to bind to DIFFERENT objects based on the purpose.

I am using the same window that serves two purposes. Inside my window, i have a listview that I want to bind to DIFFERENT objects based on the purpose.

Actually its just a window that takes in import files.

So initially I had this.

<ListView Grid.Row="1" Name="_lvValues" 
    DataContext="{Binding ElementName=_listbox,Path=SelectedItem}" 
    ItemsSource="{Binding Path=DataTable(from selectedItemObject)}">

For the other purpose I had to do this

<ListView Grid.Row="1" Name="_lvValues" 
    DataContext="{Binding ElementName=ClassName,Path=Object}" 
    ItemsSource="{Binding Path=DataTable(from Object)}">

I want to do this in an if/else statement during the initialization of the window (constructor). So...

if (windowType == Type1)
     // SetBinding to using listbox
else
     // SetBinding to using Object

I tried this 开发者_开发技巧After initialize component

        binding = new Binding("DataTable");
        binding.Source = new Binding("ListBox.SelectedItem");
        _lvValues.SetBinding(ListView.ItemsSourceProperty, binding);

But obviously it didn't work and i have no idea how to proceed.

Reason I need this is, the first window type there is a LIST of file, where second window type only has ONE file so it would not be right to show a listbox with just one file.

Thanks and Regards, Kev


If your Xaml is an accurate description of your binding you just need to translate it into the two resulting bindings; should be something like this for the first case:

Binding contextBinding = new Binding("SelectedItem");
contextBinding.Source = _listbox;
_lvValues.SetBinding(ListView.DataContextProperty, contextBinding);

Binding itemsBinding = new Binding("DataTable");
_lvValues.SetBinding(ListView.ItemsSourceProperty, itemsBinding);

and the second case is probably this:

Binding contextBinding = new Binding("Object");
contextBinding.Source = ClassName;
_lvValues.SetBinding(ListView.DataContextProperty, contextBinding);

Binding itemsBinding = new Binding("DataTable");
_lvValues.SetBinding(ListView.ItemsSourceProperty, itemsBinding);

(Since the ItemsSource-Binding is always the same and just depends on the DataContext you could refactor it to be outside of the if-clause or in the Xaml altogether i think)

0

精彩评论

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