C# 将属性绑定到UserControl
我和这件事有同样的问题 我也读过这篇文章,但我找不到出现此异常的原因: 我正在调用一个UserControl,其中应该调用另一个UserControl 在第一个UserControl中,我将执行以下操作C# 将属性绑定到UserControl,c#,wpf,xaml,winrt-xaml,C#,Wpf,Xaml,Winrt Xaml,我和这件事有同样的问题 我也读过这篇文章,但我找不到出现此异常的原因: 我正在调用一个UserControl,其中应该调用另一个UserControl 在第一个UserControl中,我将执行以下操作 <UserControl x:Class="TwitterUniversalHubTest1.UCGlobalTweet" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://
<UserControl
x:Class="TwitterUniversalHubTest1.UCGlobalTweet"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TwitterUniversalHubTest1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="150"
d:DesignWidth="400">
<Grid Height="Auto">
<Border Background="#FFFFFFFF" Margin="10 0 0 5" CornerRadius="2 2 15 2">
<Grid Width="380">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Tag="{Binding UserID}" Grid.Row="0" Name="ProfileInfo" Tapped="Profile_Tapped" Orientation="Horizontal" Margin="15 15 15 0">
<Grid Width="360" Margin="0 0 0 10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="75"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="50"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Height="45" Width="45" CornerRadius="5">
<Border.Background>
<ImageBrush ImageSource="{Binding ImagePath}" Stretch="UniformToFill"/>
</Border.Background>
</Border>
<StackPanel Grid.Column="1" Orientation="Vertical" Margin="0 5 0 0">
<TextBlock Text="{Binding FullName}" Foreground="Black" FontSize="18" FontWeight="Bold"></TextBlock>
<TextBlock Text="{Binding TwitterHandle}" Foreground="DarkGray" FontSize="12"/>
</StackPanel>
<Image Grid.Column="2" Source="Assets/ActionIcons/Twitter_logo_blue_32.png" Width="32" VerticalAlignment="Top"></Image>
</Grid>
</StackPanel>
<StackPanel Grid.Row="1" Margin="14.5,0,0,0" Height="Auto">
<StackPanel Name="TwContent" Tag="{Binding TweetID}" Margin="15 0 15 0" Tapped="Content_Tapped">
<local:ComplexTextPresenter x:Name="ComplexTextPresenterElement" Input="{Binding Content}" DataContext="{Binding Content}"/>
<ItemsControl ItemsSource="{Binding ContentImages}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding }" MaxWidth="350" Margin="0 0 0 5" HorizontalAlignment="Center"></Image>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Foreground="DarkGray" Text="{Binding DateSend}" FontSize="10"></TextBlock>
</StackPanel>
<StackPanel Name="ActionButtons">
<Grid Tag="{Binding TweetID}" Width="380" Height="25" Margin="0 0 0 10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" HorizontalAlignment="Center" Margin="20 0 0 0" Style="{StaticResource replyActionButton}" Tapped="Reply_Tapped"></Button>
<ToggleButton Grid.Column="2" HorizontalAlignment="Center" Style="{StaticResource retweetActionButton}" Tapped="Retweet_Tapped"></ToggleButton>
<TextBlock Grid.Column="3" HorizontalAlignment="Left" Margin="-15 0 0 0" VerticalAlignment="Center" Text="{Binding RetweetCount}" Foreground="DarkGray"/>
<ToggleButton x:Name="FavButton" Grid.Column="4" HorizontalAlignment="Center"
Style="{StaticResource likeActionButton}"
IsChecked="{Binding LikeState}"
Tapped="Favourite_Tapped"/>
<TextBlock Grid.Column="5" HorizontalAlignment="Left" Margin="-15 0 0 0" VerticalAlignment="Center" Text="{Binding LikeCount}" Foreground="DarkGray"/>
</Grid>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</Grid>
//更新:这是UCGlobalTweet.xaml.cs
public sealed partial class UCGlobalTweet : UserControl
{
private readonly NavigationHelper navigationHelper;
private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();
private readonly ResourceLoader resourceLoader = ResourceLoader.GetForCurrentView("Resources");
//passingparameter
public string MyContentProperty { get; set; }
public UCGlobalTweet()
{
this.InitializeComponent();
Init();
}
private void Init()
{
ComplexTextPresenterElement.Input = "This is where the Content string has to be....";
ComplexTextPresenterElement.OnHyperlinkCommand = new RelayCommand<object>(Execute);
}
private void Execute(object o)
{
//put here the code that can open browser
}
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
// Tap user specific content
private void Profile_Tapped(object sender, TappedRoutedEventArgs e)
{
Debug.WriteLine("I've clicked on information from Profile --> UserInfoPage");
List<object> passingParameters = new List<object>();
StackPanel st = (StackPanel)sender;
string userIDList = (string)st.Tag;
//provisional Data transfer
// get UserObject out of SearchResult, therefore I have to put the user content as a global variable to access it here, but this will require a lot of space probably...
// So for now I recall the UserObject again.
var usersResponse =
(from user in TweetContent.Connection.User
where user.Type == UserType.Lookup &&
user.UserIdList == userIDList
//user.ScreenNameList == "JoeMayo,Linq2Tweeter"
select user).ToList();
User curUser = usersResponse.FirstOrDefault();
passingParameters.Add(curUser);
(Window.Current.Content as Frame).Navigate(typeof(UserInfoPage), passingParameters);
}
// Tap tweet specific content
private void Content_Tapped(object sender, TappedRoutedEventArgs e)
{
Debug.WriteLine("I've clicked the Tweet content --> Going to TweetInfoPage");
List<object> passingParameters = new List<object>();
StackPanel ContentTapped = (StackPanel)sender;
ulong tag = (ulong)ContentTapped.Tag;
var test = TweetContent.FulltweetList;
var tweet = test.FirstOrDefault(tw => tw.TweetID == tag);
passingParameters.Add(tweet);
(Window.Current.Content as Frame).Navigate(typeof(TweetInfoPage), passingParameters);
}
//Action Buttons
private void Reply_Tapped(object sender, TappedRoutedEventArgs e)
{
Debug.WriteLine("Reply Button Tapped");
var test = (Button)sender;
e.Handled = true;
Debug.WriteLine("New State for Reply: " + test.IsPressed);
}
private void Retweet_Tapped(object sender, TappedRoutedEventArgs e)
{
Debug.WriteLine("Retweet Button Tapped");
//var test = (Button)sender;
//e.Handled = true;
//Debug.WriteLine("New State for Retweet: " + test.IsPressed);
}
private async void Favourite_Tapped(object sender, TappedRoutedEventArgs e)
{
try
{
Debug.WriteLine("Favourite Button Tapped");
ToggleButton tBtn = (ToggleButton)sender;
Grid pGrid = (Grid)tBtn.Parent;
var curTweet = TweetContent.FulltweetList.Where(tw => tw.TweetID.Equals(pGrid.Tag));
if (tBtn.IsChecked == false)
{
Debug.WriteLine("Status should be Checked: " + tBtn.IsChecked);
await TweetContent.Connection.DestroyFavoriteAsync((ulong)pGrid.Tag);
curTweet.First().LikeCount--;
}
if (tBtn.IsChecked == true)
{
Debug.WriteLine("Status should be UnChecked: " + tBtn.IsChecked);
await TweetContent.Connection.CreateFavoriteAsync((ulong)pGrid.Tag);
curTweet.First().LikeCount++;
}
}
catch (Exception ex)
{
Debug.WriteLine("Error while updating Favourite State: Message: " + ex);
}
finally
{
e.Handled = true;
}
}
private void RealLink_Clicked(object sender, RoutedEventArgs e)
{
var hyperlink = sender as Hyperlink;
if (hyperlink == null) return;
//Process.Start(hyperlink.NavigateUri.AbsoluteUri);
}
}
公共密封部分类UCGlobalTweet:UserControl
{
私有只读NavigationHelper NavigationHelper;
private readonly observedictionary defaultViewModel=new observedictionary();
私有只读ResourceLoader ResourceLoader=ResourceLoader.GetForCurrentView(“资源”);
//传递参数
公共字符串MyContentProperty{get;set;}
公共UCGlobalTweet()
{
this.InitializeComponent();
Init();
}
私有void Init()
{
complextPresentRelation.Input=“这是内容字符串必须位于的位置…”;
complextPresentRelation.OnHyperlinkCommand=新的RelayCommand(执行);
}
私有void执行(对象o)
{
//在这里输入可以打开浏览器的代码
}
公共可观测默认视图模型
{
获取{返回this.defaultViewModel;}
}
//点击用户特定内容
私有无效配置文件(对象发送器,TappedRoutedEventArgs e)
{
Debug.WriteLine(“我点击了概要文件-->用户信息页面中的信息”);
List passingParameters=新列表();
StackPanel st=(StackPanel)发送器;
字符串userIDList=(string)st.Tag;
//临时数据传输
//从SearchResult中获取UserObject,因此我必须将用户内容作为全局变量放在这里访问它,但这可能需要大量空间。。。
//所以现在我再次调用UserObject。
var用户响应=
(来自TweetContent.Connection.user中的用户)
其中user.Type==UserType.Lookup&&
user.UserIdList==UserIdList
//user.ScreenNameList==“JoeMayo,Linq2Tweeer”
选择user.ToList();
User curUser=usersResponse.FirstOrDefault();
passingParameters.Add(curUser);
(Window.Current.Content作为框架)。导航(typeof(UserInfoPage),passingParameters);
}
//点击推特特定内容
私有无效内容(对象发送方,TappedRoutedEventArgs e)
{
Debug.WriteLine(“我已经点击了Tweet内容-->转到Tweet信息页面”);
List passingParameters=新列表();
StackPanel ContentTapped=(StackPanel)发送器;
ulong tag=(ulong)ContentTapped.tag;
var test=TweetContent.FulltweetList;
var tweet=test.FirstOrDefault(tw=>tw.TweetID==tag);
passingParameters.Add(tweet);
(Window.Current.Content作为框架)。导航(typeof(TweetInfoPage),传递参数);
}
//动作按钮
私有无效回复(对象发送方,TappedRoutedEventArgs e)
{
Debug.WriteLine(“点击回复按钮”);
var测试=(按钮)发送器;
e、 已处理=正确;
Debug.WriteLine(“回复的新状态:“+test.IsPressed”);
}
私有无效转发(对象发送方,TappedRoutedEventArgs e)
{
Debug.WriteLine(“点击转发按钮”);
//var测试=(按钮)发送器;
//e、 已处理=正确;
//Debug.WriteLine(“转发的新状态:“+test.IsPressed”);
}
私有异步无效收藏夹(对象发送器,TappedRoutedEventArgs e)
{
尝试
{
Debug.WriteLine(“点击喜爱的按钮”);
ToggleButton tBtn=(ToggleButton)发送器;
Grid pGrid=(Grid)tBtn.Parent;
var curTweet=TweetContent.FulltweetList.Where(tw=>tw.TweetID.Equals(pGrid.Tag));
如果(tBtn.IsChecked==假)
{
Debug.WriteLine(“应检查状态:+tBtn.IsChecked”);
等待TweetContent.Connection.DestroyFavoriteAync((ulong)pGrid.Tag);
curTweet.First().LikeCount--;
}
如果(tBtn.IsChecked==真)
{
Debug.WriteLine(“应取消选中状态:+tBtn.IsChecked”);
等待TweetContent.Connection.createFavoriteAscync((ulong)pGrid.Tag);
curTweet.First().LikeCount++;
}
}
捕获(例外情况除外)
{
Debug.WriteLine(“更新收藏夹状态时出错:消息:“+ex”);
}
最后
{
e、 已处理=正确;
}
}
私有void RealLink_已单击(对象发送方,路由目标)
{
var hyperlink=发件人作为超链接;
如果(hyperlink==null)返回;
//Process.Start(hyperlink.NavigateUri.AbsoluteUri);
}
}
这里是complextPresenter.xaml——我刚才提到的第二个用户控件
<UserControl
x:Class="TwitterUniversalHubTest1.ComplexTextPresenter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ts="using:TwitterUniversalHubTest1"
xmlns:panel="using:Gregstoll"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400" x:Name="This">
<Grid>
<Grid.Resources>
<DataTemplate x:Key="HyperlinkDataTemplateKey">
<HyperlinkButton Padding="0" Margin="0" FontSize="12" CommandParameter="{Binding }" Command="{Binding ElementName=This, Path=OnHyperlinkCommand}" Content="{Binding Path=Content}" Foreground="Blue"/>
</DataTemplate>
<DataTemplate x:Key="LiteralDataTemplateKey">
<TextBlock Padding="0" Margin="0" FontSize="12" Text="{Binding Path=Content}"></TextBlock>
</DataTemplate>
<ts:MyDataTemplateSelector x:Key="DataTemplateSelectorKey"
LiteralDataTemplate ="{StaticResource LiteralDataTemplateKey}"
HyperlinkDataTemplate="{StaticResource HyperlinkDataTemplateKey}"/>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<ContentPresenter HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<!--<Rectangle Fill="Green" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>-->
<ListBox Margin="-5 0 0 15" Foreground="Black" ItemsSource="{Binding ElementName=This, Path=InputCollection}" ItemTemplateSelector="{StaticResource DataTemplateSelectorKey}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<panel:UniversalWrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ListBox>
</Grid>
干杯,
Ulpin绑定中没有
DataContext
,ElementName
或源代码。有几种方法可以使代码工作,我将给你最简单的方法,你可以选择其中任何一种
1) 将UserControl
的DataContext
设置为{Binding RelativeSource={RelativeSource Self}
。但这是一种糟糕的方法,因为您可能会覆盖现有的DataContext
,或者从外部代码中覆盖它
2) 命名您的UserControl
,并使用ElementName
绑定到它
Input="{Binding Content, ElementName=userControl}"
3) 使用{x:Bind}
:
Input="{x:Bind Content}"
注册属性时,应传递类型
Input="{x:Bind Content}"
class ComplexTextPresenterElement
{
public static readonly DependencyProperty InputProperty = DependencyProperty.Register("Input", typeof(string), typeof(ComplexTextPresenterElement), new PropertyMetadata(default(string), InputPropertyChangedCallback));
public static readonly DependencyProperty InputCollectionProperty = DependencyProperty.Register("InputCollection", typeof(ObservableCollection<object>), typeof(ComplexTextPresenterElement), new PropertyMetadata(default(ObservableCollection<object>)));
public static readonly DependencyProperty OnHyperlinkCommandProperty = DependencyProperty.Register("OnHyperlinkCommand", typeof(ICommand), typeof(ComplexTextPresenterElement), new PropertyMetadata(default(ICommand)));
}