用户控件的参数

本文关键字:参数 控件 用户 | 更新日期: 2023-09-27 18:10:45

我正在创建一个windows通用应用程序。我有一个列表框,其中包含我自己定义的类的对象的itemsource。在列表框的itemtemplate中,我有一个UserControl。这个UserControl包含两个按钮,这些按钮包含图像。当点击按钮时,图像应该改变,设置也应该改变。为了更改设置,我需要绑定到itemtemplate的对象,usercontrol是itemtemplate的一部分。

我如何获得作为UserControl实例源的特定项?

我读过这个:Windows Phone 8用户控制imagebutton,不同状态下使用不同图像

但是这并没有解释如何获得自定义类的对象。只有ui元素的属性。

编辑:因为我不允许给你看实际的代码(合同相关的业务),我给你做了一些示例代码。

单击usercontrol中的事件:

private void Important_Click(object sender, RoutedEventArgs e)
    {
        CustomClass customObject = ((sender as Button).DataContext as CustomClass);
        if (customObject != null)
        {
            Print.Debug("customObject : " + customObject .ToString());
        }
        else
        {
            Print.Debug("customObject is null");
        }
        Print.Debug("Important_Click: " + e);
        var resourceLoader = ResourceLoader.GetForCurrentView();
        if (isImportant)
        {
            Important.Source = new BitmapImage(new Uri(resourceLoader.GetString("Important/Source")));
            isImportant = false;
        }
        else
        {
            Important.Source = new BitmapImage(new Uri(resourceLoader.GetString("Important_enabled")));
            isImportant = true;
        }
        hasDoneWork = true;
    }

调用usercontrol的Xaml:

<DataTemplate x:Key="Template">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Name="TextBlockWithSource" TextWrapping="NoWrap" Text="{Binding Path=Source_Text}" Foreground="Black" FontSize="15" />
        <home:OptionButtons Name="ChatOptionsButton" Grid.Column="1" DataContext="{Binding Path=Source}" > <!-- trying to bind the object, not a variable within the object -->
        </home:OptionButtons  >
    </Grid>
</DataTemplate>
编辑2:忘记解释代码了。

在上面的代码片段中,OptionButtons是UserControl。DataTemplate是ListBox的ItemTemplate,它的ItemSource属性绑定到一个CustomClass对象集合。Important_Click事件是OptionButtons UserControl中按钮的点击事件,它改变了图像的来源。

用户控件的参数

ItemsControl的ItemTemplate中元素的默认继承DataContext已经引用了ItemsControl的ItemsItemsSource集合中的特定项。因此,没有必要显式设置它。

从XAML中删除DataContext绑定:

<home:OptionButtons Name="ChatOptionsButton" Grid.Column="1" />

Try

处理UserControl

中按钮的Click事件

你可以在那个用户控件中获得项绑定。

private void OnClick(object sender, RoutedEventArgs e)
{
   var item = ((sender as Button).DataContext) as yourCustomClass;
   if(item != null)
      '' do your stuff .. 
}