获取ListBox选择的项DataContext值

时间:2014-12-29 01:23:32

标签: c# wpf ms-word datacontext listboxitem

如果我的列表框包含以下Microsoft Word颜色索引,那么如何获取它的值并将其设置为颜色索引?

<ListBox x:Name="FindColorListBox" HorizontalAlignment="Left" Height="135" Margin="10,198,0,0" VerticalAlignment="Top" Width="107">
    <ListBoxItem Content="None">
        <ListBoxItem.DataContext>
            <word:WdColorIndex>wdAuto</word:WdColorIndex>
        </ListBoxItem.DataContext>
    </ListBoxItem>
    <ListBoxItem Content="Auto">
        <ListBoxItem.DataContext>
            <word:WdColorIndex>wdAuto</word:WdColorIndex>
        </ListBoxItem.DataContext>
    </ListBoxItem>
    <ListBoxItem Content="Black">
        <ListBoxItem.DataContext>
            <word:WdColorIndex>wdBlack</word:WdColorIndex>
        </ListBoxItem.DataContext>
    </ListBoxItem>
</listbox>

因此,用户点击&#34; FindColorListBox&#34;项目,说&#34;黑&#34;,我想从Word.WdColorIndex.Black获取datacontext以便设置

find.ColorIndex = Word.WdColorIndex.wdBlack

基本上我认为它是这样的:

find.ColorIndex = FindColorListBox.SelectedItem.DataContext;

但显然这不对......

1 个答案:

答案 0 :(得分:0)

嗯,你几乎拥有它:

var selectedColorIndex = (Word.WdColorIndex)(((FrameworkElement) 
     (FindColorListBox.SelectedItem)).DataContext)