如何在xaml中编写此表达式?
Binding binding = new Binding("Logo");
binding.Source = this;
binding.Converter = new ToImageConverter();
imgLogo.SetBinding(Image.SourceProperty, binding);
请注意,我不想在xaml.cs中设置DataContext = this
。我想把Source设置为这个。
提前致谢:)
修改
这是我的简单用户控件:
<UserControl x:Class="SilverlightApplication4.MainPage"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{Binding Tooltip, RelativeSource={RelativeSource Self}}"/>
</Grid>
</UserControl>
这是我的cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication4
{
public partial class MainPage : UserControl
{
public static readonly DependencyProperty ToolTipProperty
= DependencyProperty.Register("ToolTip", typeof(string), typeof(MainPage),
new PropertyMetadata(string.Empty));
public string Tooltip
{
get { return GetValue(ToolTipProperty) as string; }
set { SetValue(ToolTipProperty, value); }
}
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Tooltip = "Test tooltip.";
}
}
}
绑定不起作用。
答案 0 :(得分:2)
尝试使用“{Binding Logo,RelativeSource = {RelativeSource Self}}”(为清晰起见,省略了转换器)。
编辑: 根据您更新的代码,您需要:
<UserControl x:Class="SilverlightApplication4.MainPage"
x:Name=MyUserControl
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{Binding Tooltip, ElementName=MyUserControl}"/>
</Grid>
</UserControl>
答案 1 :(得分:0)
您应该在XAML中执行此操作:
<TextBlock Id="TextBlock1" Text="{Binding Tooltip}"/>
并在您的代码(Constructor / UserControl_Loaded)中,您应该:
TextBlock1.DataContext = this;
您可能还需要实施INotifyPropertyChanged
并在属性集中提升OnPropertyChanged
事件
为什么不想在代码中执行此操作?