简体   繁体   English

将列表框中的选定项目与数据模板绑定

[英]Binding selected item from Listbox with datatemplate

I have a ListBox with Questions and Answers which is taking data from Database . 我有一个带有问与答的ListBox ,它从Database获取数据。 Now i want to display or edit data from selected row from 'Listbox', but i have problem how to get to this row. 现在我想显示或编辑“列表框”中所选行的数据,但是我对如何到达此行有疑问。

Edit. 编辑。 Image to show what i want to do: http://imgur.com/5NHjYA4 图片以显示我想要做什么: http : //imgur.com/5NHjYA4

My View: 我的观点:

<Window x:Class="QuizMaker.MainWindow"
    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>

    <Window.Resources>
        <DataTemplate x:Key="QuestionsTemplate">
            <Grid>      
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="320" />
                    <ColumnDefinition Width="120" />
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="20" />
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Text="{Binding Path=Question}" FontWeight="Bold" />
                <TextBlock Grid.Column="1" Text="{Binding Path=AnswerA}" />
                <TextBlock Grid.Column="2" Text="{Binding Path=AnswerB}"/>
                <TextBlock Grid.Column="3" Text="{Binding Path=AnswerC}"/>
                <TextBlock Grid.Column="4" Text="{Binding Path=AnswerD}"/>
                <TextBlock Grid.Column="5" Text="{Binding Path=RightAnswer}" FontWeight="Bold"/>
            </Grid>
        </DataTemplate>
    </Window.Resources>

    <Grid>        
        <ListBox  DataContext="{Binding MyDataSet}" 
                  x:Name="listBox"   
                  ItemsSource="{Binding Path=QuestionTable}"
                  ItemTemplate="{StaticResource QuestionsTemplate}" 
                  SelectedItem="{Binding SelectedItemString}"             
        />

    </Grid>
</Window>

And ViewModel(I cut most of properties) 和ViewModel(我削减了大部分属性)

{
    class MainViewModel
    {
        private string _appPath;

        private MainModel _MainModel;


        public MainViewModel()
        {
            _MainModel = new MainModel();


            mdbFile = Path.Combine(AppDataPath, "QuestionBase.mdb");
            connString = $"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={mdbFile}";
            conn = new OleDbConnection(connString);

            adapter = new OleDbDataAdapter("SELECT * FROM QuestionTable;", conn);

            MyDataSet = new DataSet();
            adapter.Fill(MyDataSet, "QuestionTable");


        }

        private void AddToDB()
        {
            conn.Open();
            OleDbCommand myCommand = new OleDbCommand("Insert INTO QuestionTable ( Question, AnswerA, AnswerB, AnswerC, AnswerD ) Values(@Question, @AnswerA, @AnswerB, @AnswerC, @AnswerD)", conn);
            myCommand.Parameters.Add("@Question", OleDbType.BSTR).Value = Question;
            myCommand.Parameters.Add("@Question", OleDbType.BSTR).Value = AnswerA;
            myCommand.Parameters.Add("@Question", OleDbType.BSTR).Value = AnswerB;
            myCommand.Parameters.Add("@Question", OleDbType.BSTR).Value = AnswerC;
            myCommand.Parameters.Add("@Question", OleDbType.BSTR).Value = AnswerD;
            myCommand.ExecuteNonQuery();
            conn.Close();
        }

        private string AppDataPath
        {
            get
            {
                if (string.IsNullOrEmpty(_appPath))
                {
                    _appPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                }
                return _appPath;
            }
        }

        public OleDbDataAdapter adapter
        {
            get
            {
                return _MainModel.adapter;
            }
            set
            {
                _MainModel.adapter = value;
                OnPropertyChanged("adapter");
            }
        }
        public DataSet MyDataSet
        {
            get
            {
                return _MainModel.MyDataSet;
            }
            set
            {
                _MainModel.MyDataSet = value;
                OnPropertyChanged("MyDataSet");
            }
        }
    public string SelectedItemString
    {
        get
        {
            return _MainModel.SelectedItemString;
        }
        set
        {
            _MainModel.SelectedItemString = value;
            OnPropertyChanged("SelectedItemString");
        }
    }


        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }





    }
}

Sorry I couldn't add a comment. 抱歉,我无法添加评论。 I hope your requirement is to show the selected item's value in the TextBox and update the same value into your collection(in your case DataTable) as you change value from the TextBox. 我希望您的要求是在TextBox中显示所选项目的值,并在您从TextBox更改值时将相同的值更新到您的集合(在您的情况下为DataTable)中。 If that is your requirement change your TextBox bindings like this 如果这是您的要求,请像这样更改您的TextBox绑定

<TextBox x:Name="ValueText" Text="{Binding SelectedItem.ColumnName, ElementName=listBox, UpdateSourceTrigger=PropertyChanged}" />

I don't know why you are binding SelectedItem to string type SelectedItemString property. 我不知道您为什么将SelectedItem绑定到字符串类型SelectedItemString属性。 It will create binding error as per your source. 它将根据您的来源创建绑定错误。

Change your SelectedItemString property to a DataRow , and bind your other controls to that. 将您的SelectedItemString属性更改为DataRow ,然后将其他控件绑定到该行。

For example, 例如,

public DataRow SelectedItem
{
    get
    {
        return _MainModel.SelectedItem;
    }
    set
    {
        _MainModel.SelectedItem = value;
        OnPropertyChanged("SelectedItem");
    }
}

And in XAML should be something like this : 在XAML中应该是这样的:

<Window x:Class="QuizMaker.MainWindow"
    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>

    <Window.Resources>
        <DataTemplate x:Key="QuestionsTemplate">
            <Grid>      
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="320" />
                    <ColumnDefinition Width="120" />
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="20" />
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Text="{Binding Path=Question}" FontWeight="Bold" />
                <TextBlock Grid.Column="1" Text="{Binding Path=AnswerA}" />
                <TextBlock Grid.Column="2" Text="{Binding Path=AnswerB}"/>
                <TextBlock Grid.Column="3" Text="{Binding Path=AnswerC}"/>
                <TextBlock Grid.Column="4" Text="{Binding Path=AnswerD}"/>
                <TextBlock Grid.Column="5" Text="{Binding Path=RightAnswer}" FontWeight="Bold"/>
            </Grid>
        </DataTemplate>
    </Window.Resources>

    <DockPanel>   
        <ContentControl Content="{Binding SelectedItem}" 
                        ContentTemplate="{StaticResource QuestionsTemplate}" 
                        DockPanel.Dock="Top" />  

        <ListBox  DataContext="{Binding MyDataSet}" 
                  x:Name="listBox"   
                  ItemsSource="{Binding Path=QuestionTable}"
                  ItemTemplate="{StaticResource QuestionsTemplate}" 
                  SelectedItem="{Binding SelectedItem}"             
        />

    </DockPanel>
</Window>

Also if you really don't want to change the way you track your selected item, you could also bind directly to listBox.SelectedItem like Davys said 另外,如果您真的不想更改跟踪所选项目的方式,则也可以直接绑定到listBox.SelectedItemlistBox.SelectedItem 所说的那样。

<ContentControl Content="{Binding ElementName=listBox, Path=SelectedItem}" 
                ContentTemplate="{StaticResource QuestionsTemplate}" 
                DockPanel.Dock="Top" />  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM