我是新手,所以我不确定我的代码有什么问题。 x:Bind在MainPage()方法中工作正常但在button_click事件中不起作用。
在button_click事件中,仅填充第二个RichTextBox,但在MainPage()方法中,将填充两个RichTextBox。我不能在button_click事件上绑定而不能在MainPage()方法中绑定。
由于
Citati cit;
public MainPage()
{
// DateTime dat = DateTime.Now;
this.InitializeComponent();
// cit = new Citati();
// int dan = dat.DayOfYear;
// cit.Citiranje(dan);
// stpCitat.DataContext = cit;
//Works for both RichTextBoxes
}
private void btnPopulate_Click(object sender, RoutedEventArgs e)
{
DateTime dat = DateTime.Now;
cit = new Citati();
int dan = dat.DayOfYear;
cit.Citiranje(dan);
stpCitat.DataContext = cit;
//Works only for second RichTextBox
}
<StackPanel x:Name="stpCitat">
<RichTextBlock x:Name="rtbFirst" >
<Paragraph Margin="50,0,0,0" FontSize="21.333" >
<Run Text="{x:Bind cit.Citat}" Foreground="#FFE02323"></Run>
</Paragraph>
<Paragraph Margin="200,0,0,0">
<Hyperlink NavigateUri="{x:Bind cit.Wiki, Mode=OneWay}" >
<Run Text="{x:Bind cit.Slikar}" >
</Run>
</Hyperlink>
</Paragraph>
</RichTextBlock>
<RichTextBlock x:Name="rtbSecond" >
<Paragraph Margin="50,0,0,0" FontSize="21.333" >
<Run Text="{Binding Citat}"></Run>
</Paragraph>
<Paragraph Margin="200,0,0,0">
<Hyperlink NavigateUri="{Binding Wiki}" >
<Run Text="{Binding Slikar}" >
</Run>
</Hyperlink>
</Paragraph>
</RichTextBlock>
<Button x:Name="btnPopulate" Click="btnPopulate_Click">
</StackPanel>
答案 0 :(得分:1)
由于以下两个原因,代码无法运作:
cir
不是依赖属性,也不是INotifyPropertyChanged
属性。第二个框已更新,因为您将新的cin
分配给DataContext
,这是一个依赖项属性。x:Bind
默认模式为OneTime
,因此如果属性或数据上下文发生更改,则绑定不会更新。因此,为了使此代码有效,您需要执行以下操作:
Citati
。Mode=OneWay
。以下代码可以帮助您:
public static readonly DependencyProperty CinProperty =
DependencyProperty.Register("Cin", typeof(Citati),
typeof(MainPage), new FrameworkPropertyMetadata(null));
public Citati Cin
{
get { return (Citati)GetValue(CinProperty); }
set { SetValue(CinProperty, value); }
}
private void btnPopulate_Click(object sender, RoutedEventArgs e)
{
var dat = DateTime.Now;
var cit = new Citati();
int dan = dat.DayOfYear;
cit.Citiranje(dan);
stpCitat.DataContext = cit;
Cit = cit;
}
标记:
<RichTextBlock x:Name="rtbFirst" >
<Paragraph Margin="50,0,0,0" FontSize="21.333" >
<Run Text="{x:Bind Cit.Citat, Mode=OneWay}" Foreground="#FFE02323"/>
</Paragraph>
<Paragraph Margin="200,0,0,0">
<Hyperlink NavigateUri="{x:Bind cit.Wiki, Mode=OneWay}" >
<Run Text="{x:Bind Cit.Slikar, Mode=OneWay}"/>
</Hyperlink>
</Paragraph>
</RichTextBlock>