gpt4 book ai didi

c# - 从 FrameworkElementFactory 获取值

转载 作者:太空宇宙 更新时间:2023-11-03 11:16:52 25 4
gpt4 key购买 nike

我有一个带有一个 GridViewColumn 的 ListView

        GridViewColumn gvc = new GridViewColumn();

DataTemplate dt = new DataTemplate();
FrameworkElementFactory ch = new FrameworkElementFactory(typeof(CheckBox));

Binding bind= new Binding("Empty");
ch.SetBinding(CheckBox.IsCheckedProperty, bind);

dt.VisualTree = ch;
gvc.CellTemplate = dt;
(lv.View as GridView).Columns.Add(gvc);

稍后,当我想检索复选框是否被选中时,我面对的是 FrameworkElementFactory,因为它没有 GetValue 方法,不知道如何将其转换为复选框,所以如何才能我从 FrameworkElementFactory 获取 IsChecked 属性,我知道我的 ListView 的任何元素都可以访问它

 ...
var mycheckboxFEF = template.VisualTree.FirstChild;// FirstChild is my FrameWorkElementFactory checkbox
bool isempty= (......) ????

最佳答案

我确实通过这个例子为您的问题提供了解决方案。
这应该通过选择一个项目并按下按钮来工作
XAML :

<Button Margin="0,12,401,276" Click="Button_Click">Button</Button>
<ListView x:Name="yourListView" ItemsSource="{Binding Things}" SelectedItem="{Binding SelectedThing}" Margin="0,41,0,0">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Check" Width="250">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="myCBox" Content="{Binding ThingName}"></CheckBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>

代码隐藏:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

Things = new List<Thing>
{
new Thing {ThingName = "t1"},
new Thing {ThingName = "t2"},
new Thing {ThingName = "t4"},
new Thing {ThingName = "t3"},
};
DataContext = this;

}

public List<Thing> Things { get; set; }
public Thing SelectedThing { get; set; }

private void Button_Click(object sender, RoutedEventArgs e)
{
var yourListViewItem = (ListViewItem)yourListView.ItemContainerGenerator.ContainerFromItem(yourListView.SelectedItem);
CheckBox cb = FindByName("myCBox", yourListViewItem) as CheckBox;
MessageBox.Show(cb.Content + " IsChecked :" + cb.IsChecked);
}
private FrameworkElement FindByName(string name, FrameworkElement root)
{
Stack<FrameworkElement> tree = new Stack<FrameworkElement>();
tree.Push(root);

while (tree.Count > 0)
{
FrameworkElement current = tree.Pop();
if (current.Name == name)
return current;

int count = VisualTreeHelper.GetChildrenCount(current);
for (int i = 0; i < count; ++i)
{
DependencyObject child = VisualTreeHelper.GetChild(current, i);
if (child is FrameworkElement)
tree.Push((FrameworkElement)child);
}
}

return null;
}
}



public class Thing
{
public string ThingName { get; set; }

}

希望对你有帮助

关于c# - 从 FrameworkElementFactory 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com